Python 将多个文件中的文本读取/写入主文件

Python 将多个文件中的文本读取/写入主文件,python,Python,在下面的代码中,我试图打开一系列文本文件,并将其内容复制到单个文件中。我在“os.write(out\u file,line)”中遇到一个错误,它要求我输入一个整数。我还没有定义“线”是什么,这就是问题所在吗?我是否需要以某种方式指定“line”是in_文件中的文本字符串?此外,我还通过for循环的每次迭代打开out_文件。那么糟糕吗?我应该一开始就打开一次吗?谢谢 import os import os.path import shutil # This is supposed to rea

在下面的代码中,我试图打开一系列文本文件,并将其内容复制到单个文件中。我在“os.write(out\u file,line)”中遇到一个错误,它要求我输入一个整数。我还没有定义“线”是什么,这就是问题所在吗?我是否需要以某种方式指定“line”是in_文件中的文本字符串?此外,我还通过for循环的每次迭代打开out_文件。那么糟糕吗?我应该一开始就打开一次吗?谢谢

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()
或者,更通俗地说:

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"

另外,我正在从书本上自学python,这样我就可以作为一名研究生进行研究,所以这个问题可能有点初级。提前谢谢!我建议您使用os.path.join(path,f_name)来正确构建完整的路径文件名:in_file=open(os.path.join(path,f_name),'r')我已经有一段时间没有发布我的问题了,但回来时我注意到它被否决了。如能就如何更好地提问提出建议,我将不胜感激。