-1
在下面的代碼中,我試圖打開一系列文本文件並將其內容複製到一個文件中。我在「os.write(out_file,line)」中得到一個錯誤,在這個錯誤中它詢問我一個整數。我還沒有定義「線路」是什麼,那麼這個問題呢?我是否需要以某種方式指定「line」是來自in_file的文本字符串?另外,我通過for循環的每次迭代打開out_file。那不好嗎?我應該在開始時打開一次嗎?謝謝!從多個文件讀取/寫入文本到主文件
import os
import os.path
import shutil
# This is supposed to read through all the text files in a folder and
# copy the text inside to a master file.
# This defines the master file and gets the source directory
# for reading/writing the files in that directory to the master file.
src_dir = r'D:\Term Search'
out_file = r'D:\master.txt'
files = [(path, f) for path,_,file_list in os.walk(src_dir) for f in file_list]
# This for-loop should open each of the files in the source directory, write
# their content to the master file, and finally close the in_file.
for path, f_name in files:
open(out_file, 'a+')
in_file = open('%s/%s' % (path, f_name), 'r')
for line in in_file:
os.write(out_file, line)
close(file_name)
close(out_file)
print 'Finished'
另外,我自學Python從書本和這樣的,所以我可以做我的研究作爲一個研究生所以這個問題可能對事物的初學者來說是一點點時間。提前致謝! – user1252778
我建議你使用os.path.join(path,f_name)正確構建完整的路徑文件名:in_file = open(os.path.join(path,f_name),'r') –
已經有一段時間了,我發佈了我的問題,但在回來後我發現它被低估了。任何建議,我可以做什麼來更好地問我的問題,將不勝感激。 – user1252778