gpt4 book ai didi

python - Shutil.copy 只能运行一次

转载 作者:太空宇宙 更新时间:2023-11-04 04:06:29 24 4
gpt4 key购买 nike

作为一名 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()

有人可以告诉我,为什么当我删除创建的文件夹并尝试再次运行该脚本时,该脚本无法重现,以及我可以采取哪些措施来实现这一点?

我知道这有点困惑,但这将是一个更大脚本的一部分,而且我仍处于初稿阶段!!

非常感谢

最佳答案

这有效:

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 然后会将您的文件复制到该目录

关于python - Shutil.copy 只能运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20983193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com