在Python中将文件从一个文件夹移动到另一个文件夹并返回
我对python比较陌生,我正在做一些项目。假设我在Windows上的分区D上运行脚本,例如,它是“D:/quantial.py” 我现在正在寻找的是:在Python中将文件从一个文件夹移动到另一个文件夹并返回,python,os.path,Python,Os.path,我对python比较陌生,我正在做一些项目。假设我在Windows上的分区D上运行脚本,例如,它是“D:/quantial.py” 我现在正在寻找的是: 从一个文件夹(比如桌面)中取出一个文件并将其移动到另一个文件夹(比如C:\quantial)——但我需要从键盘读取文件和目录。C:\quantial文件夹在前面创建时使用以下代码: 在移动文件之前,我需要以某种方式存储文件以前的位置。我正在考虑在C:\quantial文件夹中创建一个.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 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)
去看看这个链接:它有很多信息可以帮助你。另外,请看:老实说,我认为我需要比日志模块更基本的文件;我当前导入的文本文件不需要一次保存超过1个路径:import os、errno、sys、os.path。但是我不明白在我的情况下如何使用os.system()函数,你能详细说明一下吗?我使用linux,所以我会在它->os.system(“ls”)中给你一个例子,它将使命令ls在终端中工作,我的观点是它可能在CMD中工作类似对不起,我仍然不明白,这如何应用于我的问题?在函数中,您创建。打开(执行)一个xyz.py文件,该文件将把文件恢复到原来的位置
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)