作为一名Python初学者,我遇到了移动文件的实际问题。下面是我最终(!)制作的脚本,它只是将选择的文件从选择的目录移动到新文件夹。 由于某些我无法理解的原因,它只运行一次,然后创建的目标文件夹真的很奇怪。有一次,它创建了一个“目录”,它是一个具有正确名称的未知应用程序,有时它使用看似随机的文件创建一个文本文件来生成内容 - 它创建的文件再次被正确命名。
以下是相关脚本:
#!/usr/bin/python
import os, shutil
def file_input(file_name):
newlist = [] #create new list
for names in os.listdir(file_name): #loops through directory
if names.endswith(".txt") or names.endswith(".doc"): #returns only extensions required
full_file_name = os.path.join(file_name, names) #creates full file path name - required for further file modification
newlist.append(full_file_name) #adds item to list
dst = os.path.join(file_name + "/target_files")
full_file_name = os.path.join(file_name, names)
if (os.path.isfile(full_file_name)):
print "Success!"
shutil.copy(full_file_name, dst)
def find_file():
file_name = raw_input("\nPlease carefully input full directory pathway.\nUse capitalisation as necessary.\nFile path: ")
file_name = "/root/my-documents" #permanent input for testing!
return file_input(file_name)
'''try:
os.path.exists(file_name)
file_input(file_name)
except (IOError, OSError):
print "-" * 15
print "No file found.\nPlease try again."
print "-" * 15
return find_file()'''
find_file()
有人可以告诉我为什么当我删除创建的文件夹并尝试再次运行它时,此脚本不可重现,以及我可以做些什么来实现这一目标?
我知道这有点乱,但这是一个更大的剧本的一部分,我还处于初稿阶段!!
非常感谢
答案 0 :(得分:0)
这有效:
import os, shutil
def file_input(file_name):
newlist = [] #create new list
for names in os.listdir(file_name): #loops through directory
if names.endswith(".txt") or names.endswith(".doc"): #returns only extensions required
full_file_name = os.path.join(file_name, names) #creates full file path name - required for further file modification
newlist.append(full_file_name) #adds item to list
dst = os.path.join(file_name + "/target_files")
if not os.path.exists(dst):
os.makedirs(dst)
full_file_name = os.path.join(file_name, names)
if (os.path.exists(full_file_name)):
print "Success!"
shutil.copy(full_file_name, dst)
def find_file():
file_name = raw_input("\nPlease carefully input full directory pathway.\nUse capitalisation as necessary.\nFile path: ")
file_name = "/home/praveen/programming/trash/documents" #permanent input for testing!
return file_input(file_name)
find_file()
您需要检查您的复制目标目录是否确实存在,如果没有创建它。然后shutil.copy会将您的文件复制到该目录