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

Moving a file from one folder to another and back in Python

我是 python 的新手,我正在做几个项目。假设我是 运行 Windows 分区 D 上的脚本,所以,例如,它是 "D:/quarantine.py"

我现在要找的是:

  1. 从一个文件夹(比如 Desktop)中获取文件并将其移动到另一个文件夹(比如 C:\Quarantine)- 但我需要从键盘读取文件和目录。 C:\Quarantine 文件夹是之前使用以下代码创建的:
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:\Quarantine 文件夹中创建一个 .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 是我之前用来读取隔离文件夹位置的变量,所以我想我可以重用它。至于读取日志文件和恢复,我就不知道了。

有人能帮忙吗?

您可以通过从 os 导入来使用 os.system() 函数。它将在 cmd/shell 中执行命令,但仅针对子进程。 希望对您有所帮助

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

主要:

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...")

移动:

def move(filepath):

f = open('quar_id.txt','w')
f.write(path)
f.close()
os.chdir(dir_name)
shutil.move(file_path,dir_name+'/'+file)

恢复:

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)