Home > database >  Writing a function that numbers lines in a txt file skipping blank lines and writing the output to a
Writing a function that numbers lines in a txt file skipping blank lines and writing the output to a

Time:09-22

As the title says I need to create a function that reads a file and numbers the lines in that file, skipping over blank lines, and then writes that output into another file. This is what I have so far but I'm pretty new so I'm not sure what I'm doing.

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

There are some other cells that checks your work and I get the error AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

CodePudding user response:

The issue is that you are opening the file but arent reading it so you don't actually have the object you need to be splitting the file into the parts you want it to. You can fix this by just adding an extra variable like this:

g = f.read()

add this after you open the file then change

lines = f.split("\n")

to

lines = g.split("\n")

CodePudding user response:

@pynoob first off try using with.open() instead of regular open. It will make following your code much easier and will cause less bugs when you forget to close files as it handles all that for you. Second, when you open the file with open() its an object that hasn't be had its data read yet so you need to get the data from it before you can use it. Then you can also use things like f-strings to make it nice and easy!

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
    
  • Related