在Python中将文件从一个文件夹移动到另一个文件夹并返回

2024-06-16 10:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python比较陌生,我正在做一些项目。假设我在Windows上的分区D上运行脚本,例如,它是“D:/检疫.py““

我现在要找的是:

  1. 从一个文件夹(比如桌面)中取出一个文件并将其移动到另一个文件夹(比如,C:\quantilation)——但是我需要从键盘上读取文件和目录。C:\隔离区文件夹是在前面创建的,代码如下:
def create_quar(quar_folder):
    try:
        os.makedirs(quar_folder)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise


dir_name = input("Enter the desired quarantine path: ")
if os.path.isdir(dir_name):
    print ("Directory already existed.")
else:
    print ("Directory created successfully!")
create_quar(dir_name)
  1. 在移动文件之前,我需要以某种方式存储文件的先前位置。我在考虑在C:\quantilation文件夹中创建一个.txt文件。

  2. 如果我改变主意,我会调用一个函数来读取我之前创建的.txt文件,然后将这些文件移回原始文件夹。这,我不知道如何实施。

我不知道如何着手做这件事。正在考虑这样的方法来记录路径并移动文件:

path = input("Directory of file I need to move: ")
file = input("File name: ")
f = open(dir_name+"\log.txt",'w')
f.write(os.path.abspath(path+file))
shutil.move(path+file,dir_name+file)

dir_name是我之前用来读取隔离文件夹位置的变量,所以我想我可以重用它。至于读取日志文件和恢复,我不知道。在

有人能帮忙吗?在


Tags: 文件pathnametxt文件夹inputoscreate
2条回答

好吧,最后我还是自己完成了。如果有人感兴趣,您可以找到下面的代码示例。它非常简单,当然可以优化,但它确实有效。在

主要:

def Main():

dir_name = input("Enter the destination path: ")
if os.path.isdir(dir_name):
    print ("Directory already existed.")
else:
    print ("Directory created successfully!")
os.makedirs(dir_name)

choice = input("Would you like to (M)ove or (R)estore?: ")

if choice == 'M':
    path = input("Directory of file you want moved: ")
    file = input("Name of the file+extension: ")
    file_path = path+'/'+file
    move(file_path)
    print ("Done.")

elif choice == 'R':
    with open('quar_id.txt') as f:
        quar_id = f.readline()
    restore_from_quar(quar_id)
    print ("Done.")

else: 
    print ("No valid option selected, closing...")

移动:

^{pr2}$

还原:

def restore(quar_id):

os.chdir(dir_name)
myfile = os.listdir(dir_name)
file = str(myfile)
file = file[2:-2]
shutil.move(file,quar_id+'/'+file)

你可以用操作系统()从操作系统导入。它将在cmd/shell中执行命令,但仅针对子进程。 我希望这是有益的

相关问题 更多 >