在下面的代码中,它将out_file作为字符串读取,我似乎无法弄清楚原因。如果我不将其视为字符串,则表示文件位置不正确。它显然很好地读取了src_dir。在此先感谢您的帮助。我是python的新手并且自学。
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 gets the source and target directories for reading writing the
# files respectively
src_dir = r'E:\filepath\text_files'
out_file = r'E:\filepath\master.txt'
files = (os.listdir(src_dir))
def valid_path(dir_path, filename):
full_path = os.path.join(dir_path, filename)
return os.path.isfile(full_path)
file_list = [os.path.join(src_dir, f) for f in files if valid_path(src_dir, f)]
# This should open the directory and make a string of all the files
# listed in the directory. I need it to open them one by one, write to the
# master file and close it when completely finished.
open(out_file, 'a+')
with out_file.open() as outfile:
for element in file_list:
open(element)
outfile.append(element.readlines())
out_file.close()
print 'Finished'
答案 0 :(得分:1)
这是错的:
open(out_file, 'a+')
with out_file.open() as outfile:
for element in file_list:
open(element)
outfile.append(element.readlines())
out_file.close()
open
,read
,write
,readlines
的正确用法是:
f = open(path_to_file, ...)
f.write(data)
data = f.read()
lines = f.readlines()
f.close()
[以上不是有效或有效的脚本,只是如何调用每个方法的示例]
为了帮助您解决特定用例:
with open(out_file, 'a+') as outfile:
for element in file_list:
with open(element) as infile:
outfile.write(infile.read())
如果您使用close()
关闭(with
的全部内容,那么您不需要with
:它会为您关闭。)
由于您想要从一个文件中读取所有内容并写入另一个文件,因此请使用read()
而不是readlines()
:即获取全部内容,写下全部内容。
如果你真的想使用readlines()
,那么这样的事情会更好:
outfile.write(''.join(infile.readlines())