[英]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.