【问题标题】:Moving a file from one folder to another and back in Python在 Python 中将文件从一个文件夹移动到另一个文件夹并返回
【发布时间】:2017-06-27 18:16:40
【问题描述】:

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

我现在正在寻找的是:

  1. 从一个文件夹(例如桌面)获取文件并将其移动到另一个文件夹(例如 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 是我之前用来读取隔离文件夹位置的变量,所以我想我可以重复使用它。至于读取日志文件和恢复,我不知道。

谁能帮忙?

【问题讨论】:

标签: python os.path


【解决方案1】:

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

【讨论】:

  • 我目前正在导入:import os, errno, sys, os.path。但我不明白在我的情况下如何处理 os.system() 函数,你能详细说明一下吗?
  • 我使用 linux ,所以我将在其中举一个例子 ->os.system("ls") 它将使命令 ls 在终端中工作,我的观点是它可能在类似的情况下工作cmd
  • 对不起,我还是不明白,这如何适用于我的问题?
  • 在函数中,你创建。打开(执行)一个 xyz.py 文件,它将文件恢复到原来的位置
【解决方案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...")

移动:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2022-10-25
    相关资源
    最近更新 更多