【问题标题】:Writing a function that numbers lines in a txt file skipping blank lines and writing the output to another file编写一个对txt文件中的行进行编号的函数,跳过空白行并将输出写入另一个文件
【发布时间】:2021-11-13 06:31:58
【问题描述】:

正如标题所说,我需要创建一个函数来读取文件并为该文件中的行编号,跳过空白行,然后将该输出写入另一个文件。这是我到目前为止所拥有的,但我很新,所以我不确定我在做什么。

def num_lines(inputfilename, outputfilename):
    f = open(inputfilename, 'r')
    lines = f.split("\n")
    num_lines = list()
    for line in lines:
        if line == " ":
            num_lines.append(str(len(num_lines))+ "  " + line + "\n")
    fout = open(outputfilename, 'w')
    fout.write(str("\n".join(num_lines)))
    fout.close()

还有其他一些单元格检查您的工作,但我收到错误消息 AttributeError: '_io.TextIOWrapper' 对象没有属性 'split'

【问题讨论】:

    标签: python file write


    【解决方案1】:

    问题是您正在打开文件但没有读取它,因此您实际上没有将文件拆分为所需部分的对象。你可以通过像这样添加一个额外的变量来解决这个问题:

    g = f.read()
    

    打开文件后添加,然后更改

    lines = f.split("\n")
    

    lines = g.split("\n")
    

    【讨论】:

      【解决方案2】:

      @pynoob 首先尝试使用 with.open() 而不是常规打开。当您忘记关闭文件时,它将使您的代码更加容易,并且会减少错误,因为它会为您处理所有这些。其次,当您使用 open() 打开文件时,它是一个尚未读取数据的对象,因此您需要先从中获取数据才能使用它。然后你也可以使用 f-strings 之类的东西让它变得又好又简单!

      def num_lines(inputfilename, outputfilename):
          page_num = 1
          with open(inputfilename, 'r') as in_file:
              lines = in_file.readlines()
              for line in lines:
                  if line != '\n':
                      with open(outputfilename, 'a+') as out_file:
                          out_file.write(f'{page_num}. {line.replace("/n","")}')
                          page_num +=1
          
      

      【讨论】:

      • hmm 这仍然给我断言单元格中的错误 ---> 19 assert_equal(line[0], '0') # 检查行中的第一个单词。 'a+' 应该做什么?
      • @pynoob 你能给我你的完整追溯吗?和 a+ 用于读取和附加文件。如果文件不存在,它将创建它。
      • AssertionError Traceback(最近一次调用最后)/var/folders/p5/vj203w_s7fn3wwzxfj69n33c0000gn/T/ipykernel_87319/52429652.py 在 17 行 = fin.readlines() 18 行 = 行[0 ].split(' ') ---> 19 assert_equal(line[0], '0') # 检查第 20 行的第一个单词 assert_equal(line[-1], 'eros.\n') # 检查最后一个单词line 21 assert_equal(lines[1], '\n') # 检查空行 AssertionError: '5.' != '0' - 5. + 0
      猜你喜欢
      • 2016-06-18
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多