[英]Reading/Writing Text from Multiple Files to Master File
在下面的代碼中,我試圖打開一系列文本文件並將其內容復制到一個文件中。 我在“ os.write(out_file,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'
你這樣做是錯的:
您做了:
open(out_file, 'a+')
但這不會將引用另存為變量,因此您無法訪問剛剛創建的文件對象。 你需要做什么:
out_file_handle = open(out_file, 'a+')
...
out_file_handle.write(line)
...
out_file_handle.close()
或者,更Python化地:
out_filename = r"D:\master.txt"
...
with open(out_filename, 'a+') as outfile:
for filepath in files:
with open(os.path.join(*filepath)) as infile:
outfile.write(infile.read())
print "finished"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.