[英]Python: error when trying to write or overwrite a text file in a directory
我写了一个由两个函数组成的python脚本:
note():在名为target_dir的目录中写入文本文件。
file_exist():检查target_dir中是否已经存在以字符串“ note”开头的文本文件。 如果是这种情况,我想通过再次运行note()函数来覆盖文本文件。 这是代码:
import glob, os, shutil, time
def note():
""" Write the info a in a txt file"""
print 'Please enter few info:\n '
a = raw_input('Aim: ')
add = raw_input('Additional info: ')
file_name = 'note_' + time.strftime('%d%m%Y') + '.txt' #which is: note_23112015.txt
myfile = open(file_name, 'w')
myfile.write('Aim: '+ a +'\n')
myfile.write('Additional info: '+ add +'\n')
myfile.close()
shutil.copy2(file_name, target_dir)
def file_exist():
"""Check if a file starting with the string 'note' already exist."""
txt = [i for i in os.listdir(target_dir) if os.path.isfile(os.path.join(target_dir,i)) and 'note' in i]
if txt:
inp = raw_input('Text File already exist, do you want overwrite?(y or n)')
if inp == 'y':
note()
else:
note()
if __name__ == "__main__":
# Change the directory path
target_dir = 'C:/Users/data' # target directory
file_exist()
当我尝试运行脚本时,将正确生成文本文件,但同时还会出现一堆以以下结尾的错误:
Error: note_23112015.txt and `C:/Users/data\note_23112015.txt` are the same file
有人知道这段代码有什么问题吗? 谢谢
在shutil.copy2(file_name, target_dir)
,您正在将文件复制到它已经在的路径中。
1)更改目标目录或搜索目录(当前是从您的工作目录中提取),以使它们彼此不匹配
要么
2)更改输出文件的名称。
但是,重新阅读您的描述后,听起来好像您可以完全删除copy2行。 您需要更新文件的两个副本吗?
编辑:
根据OP的要求,我将用以下代码编写代码:
shutil.copy2(file_name, target_dir)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.