-1

以下のコードでは、一連のテキスト ファイルを開いて、その内容を 1 つのファイルにコピーしようとしています。整数を要求する「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'
4

1 に答える 1

3

あなたは間違っています:

あなたがした:

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"
于 2012-10-18T16:33:12.803 に答える