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

时间:2017-06-27 18:16:40

标签: python os.path

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

我现在正在寻找的是:

  1. 从一个文件夹(例如桌面)获取文件并将其移动到另一个文件夹(例如,C:\ Quarantine) - 但我需要从键盘读取文件和目录。之前使用以下代码创建了C:\ Quarantine文件夹:
  2. 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文件,然后将文件移回原始文件夹。这个,我不知道如何实施。

    3. 我不知道如何去做这件事。正在考虑这样的事情来记录路径和移动文件:

      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是我之前用来读取Quarantine文件夹位置的变量,所以我想我可以重用它。至于阅读日志文件和恢复,我不知道。

      有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

好吧,所以我最终成功地做到了这一点。如果有人感兴趣,您将在下面找到代码示例。它非常简陋,当然可以进行优化,但确实有效。

主:

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)
相关问题