3

簡単そうなことを成し遂げようとしていますが、理解できないようです。私はPythonの新人です。

これが私のタスクです:
それぞれが別々の行にある番号のリストを含むテキストファイルがあります...

100101
100201
100301
100401
100501
100601
100701
100801
100901
101001

私がやりたいのは、テキストファイルから読み取り、その行を含み、その行を使用して名前が付けられているファイルの各行に新しいテキストファイルを書き込むことです...

100101.txt
contains one line of text "100101"

100201.txt
contains one line of text "100201"

etc...

これが理にかなっていることを願っています...ありがとう!

hjnathan

4

3 に答える 3

5

これを試して:

with open('data.txt') as inf:
    for line in inf:
        num = line.strip()
        if num:
            fn = '%s.txt' %num
            with open(fn, 'w') as outf:
                outf.write('contains one line of text "%s"\n' %num)

コンストラクトを使用するwithと、不要になった場合 (または例外が発生した場合) に各ファイルが確実に閉じられます。

于 2012-07-27T19:21:36.350 に答える
3

編集:with実行をより安全にするために使用されます。

lines = open(your_file, 'r')
for line in lines.readlines():
    with open(str(line).rstrip()+'.txt','w') as output_file
        output_file.write(line)
lines.close()
于 2012-07-27T19:11:13.753 に答える
2

以下では、同じ名前の既存のファイルはチェックされないことに注意してください。

with open('numbers_file.txt','r') as numbers:
    for line in numbers:
        with open(line.rstrip() + '.txt','w') as new_file:
            new_file.write(line)
于 2012-07-27T19:08:35.637 に答える