Python 对文本文件中多行的函数

Python function to multiple individual lines in text file

我正在尝试编写一个函数,它可以获取 txt 文件中的每一行并将该行乘以 2,以便文本文件中的每个整数都加倍。到目前为止,我能够获得要打印的代码。但是,当我添加代码(读取 & reading_int)以将字符串转换为整数时,该函数现在无法正常工作。代码中没有错误可以告诉我我做错了什么。我不确定阅读和 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

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

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()

原始代码的问题:

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)