【问题标题】:How to write to text file python 3? [duplicate]如何写入文本文件python 3? [复制]
【发布时间】:2019-11-01 17:45:57
【问题描述】:

如何写入文本文件 python 3?

我想读取每一行并写入 line1 的 outputDoc1.txt ,line1 的 outputDoc2.txt ,line1 的 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()

【问题讨论】:

  • 为什么你在写一行之后关闭文件 a) 和 b) 呢? with 表达式将为您关闭文件。
  • 是否有理由需要一次向每个文件写入一行?因为现在您将执行 line1、line1、line1、line2 等。如果不需要,那么我建议您一次将所有行写入每个文件,这样您就不会在每次需要新行时都重新打开文件写出来。
  • 当前代码有什么问题,是什么问题?

标签: python


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    您在打开的文件中缺少 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 行

    【讨论】:

    • 正如你所说,它只是将第 3 行写入所有文件
    • 因为您使用的范围循环会一直持续到 for 循环列表中的最后一个元素,请按我编辑的方式尝试
    【解决方案3】:

    首先,你目前没有写你想要的行。

    改变

    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
    

    【讨论】:

      猜你喜欢
      • 2013-10-23
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2013-03-03
      • 2021-01-31
      • 1970-01-01
      • 2017-10-24
      • 2016-08-25
      相关资源
      最近更新 更多