【发布时间】:2016-02-25 18:31:07
【问题描述】:
我写了一个由两个函数组成的python脚本:
note() : 在名为 target_dir 的目录中写入文本文件。
file_exist():检查以字符串“note”开头的文本文件是否已经存在于 target_dir 中。如果是这种情况,我想通过再次运行 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)从当前目录复制到目标目录。如果当前和目标相同,它将失败。您可以使用os.path.normpath(os.path.basename(target_dir)) == os.getcwd()并跳过副本。