如何写入文本文件python 3?

时间:2019-06-19 04:18:15

标签: python

如何写入文本文件python 3?

我想读取每一行,并将其写入第1行的outputDoc1.txt,将第1行的outputDoc2.txt写入,将第1行的outputDoc3.txt写入

line1 = "Alright, I think I understand. Thank you again"
line2 = " just had to use join to separate the data"
line3 = " whether that's desirable or not I suppose is down to the OP"
path = "C:\\Users\\subashini.u\\Desktop\\"

l=["line1","line2","line3"]
count = 0
for txt_file in l:
    count += 1
    for x in range(count):
        with open(path + "outputDoc%s.txt" % x) as output_file:
            output_file.write(txt_file)
            #shutil.copyfileobj(file_response.raw, output_file)
            output_file.close()

3 个答案:

答案 0 :(得分:2)

line1 = "Alright, I think I understand. Thank you again"
line2 = " just had to use join to separate the data"
line3 = " whether that's desirable or not I suppose is down to the OP"
path = "D://foldername/"

ls=[line1,line2,line3]

for i, l in enumerate(ls, start=1):
    with open(path + "outputDoc%s.txt" % i, 'w') as output_file:
        output_file.write(l)

答案 1 :(得分:0)

您在打开文件时丢失了write属性,而是指向了字符串而不是行元素:

只是改变

循环到:

l=[line1,line2,line3]
count = 0
for txt_file in l:
    print(txt_file)
    count += 1
    with open(path + "outputDoc%s.txt" % count, 'w') as output_file:
        output_file.write(txt_file + '\n')

它写道:

<path>/outputDoc1.txt中的第1行

<path>/outputDoc2.txt行中的第2行

答案 2 :(得分:0)

首先,您当前不编写所需的行。

更改

l=["line1","line2","line3"]

l = [line1, line2, line3]

然后,为了使事情变得容易一些,您可以执行以下操作:

for i, line in enumerate(l, start=1):
    ...

要打开文件并写入内容,您需要使用正确的mode->'write'打开文件。 open()的默认模式是read,因此您当前无法写入文件。

with open('file', 'w') as f:
    ...
    # no f.close() needed here