【问题标题】:Python function to multiple individual lines in text filePython函数到文本文件中的多个单独的行
【发布时间】:2021-09-09 19:52:28
【问题描述】:

我正在尝试编写一个函数,该函数可以获取 txt 文件中的每一行并将该行乘以 2,以便文本文件中的每个整数都加倍。到目前为止,我能够打印代码。但是,当我添加代码(读取和读取整数)以将字符串转换为整数时,该函数现在不起作用。代码中没有错误可以告诉我我做错了什么。我不确定 read 和 reading_int 有什么问题导致我的功能无法正常工作。

def mult_num3():
data=[]
w = open('file3.txt', 'r')
with w as f:
    reading = f.read()
    reading_int = [int(x) for x in reading.split()]
    for line in f:
        currentline = line[:-1]
        data.append(currentline)
    for i in data:
        w.write(int(i)*2)
w.close()

file3.txt:

1
2
3
4
5
6
7
8
9
10

期望的输出:

2
4
6
8
10
12
14
16
18
20

【问题讨论】:

  • 您创建了一个整数列表reading_int = [int(x) for x in reading.split()],您从未使用过。
  • 文本文件中的每一行是否只包含可以转换为整数的字符串?...如果您发布一些示例数据会很清楚。

标签: python function multiplication txt


【解决方案1】:

原代码的问题:

def mult_num3():
    data=[]
    w = open('file3.txt', 'r')  # only opened for reading, not writing
    with w as f:
        reading = f.read()  # reads whole file
        reading_int = [int(x) for x in reading.split()] # unused variable
        for line in f:  # file is empty now
            currentline = line[:-1] # not executed
            data.append(currentline) # not executed
        for i in data:  # data is empty, so...
            w.write(int(i)*2) # not executed, can't write an int if it did
                              # and file isn't writable.
    w.close() # not necessary, 'with' will close it

请注意,int() 会忽略前导和尾随空格,因此如果每行只有一个数字,则不需要.split(),并且格式字符串(f-string)可以根据需要通过将值转换和加倍并添加来格式化每一行换行符。

with open('file3.txt', 'r') as f:
    data = [f'{int(line)*2}\n' for line in f]
with open('file3.txt', 'w') as f:
    f.writelines(data)

【讨论】:

    【解决方案2】:

    我添加了一个尝试,除了检查非整数数据。我不知道你的数据。但也许它对你有帮助。

    def mult_num3():
        input = open('file3.txt', 'r')
        output = open('script_out.txt', 'w')
    
        with input as f:
    
            for line in f:
    
                for value in line.split():
                    try:
                        output.write(str(int(value) * 2) + " ")
                    except:
                        output.write(
                            "(" + str(value + ": is not an integer") + ") ")
    
                output.write("\n")
    
        output.close()
    

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 2015-11-08
      相关资源
      最近更新 更多