Search code examples
pythonfunctionmultiplicationtxt

Python function to multiple individual lines in text file


I am trying to write a function that can take every individual line in a txt file and multiply that line by 2 so that each integer in the text file is doubled. So far I was able to get the code to print. However, when I added the code (reading & reading_int) to convert the strings to integers the function is now not working. There are no errors in the code to tell me what I am doing wrong. I am not sure what is wrong with reading and reading_int that is making my function not work.

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

Desired output:

2
4
6
8
10
12
14
16
18
20

Solution

  • Problems with original code:

    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
    

    Note that int() ignores leading and trailing whitespace so no need for .split() if only one number per line, and a format string (f-string) can format each line as needed by converting and doubling the value and adding a newline.

    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)