简体   繁体   中英

Python - Why is my for loop skipping lines and not reaching the end of the file?

I'm writing a simple function that takes the path of a text file and returns the number of lines contained in that file.

I've made sure to set the file pointer to the beginning using file.seek(0).

def get_number_lines(file_dir):

    exists = os.path.isfile(file_dir) 
    if (exists):
        print(file_dir)
        line_count = 0
        read_file  = open(file_dir,'r')
        read_file.seek(0)
        for line_num, line in enumerate(read_file.readlines()):
            line_count = line_num
            print(line)
        read_file.close()

        return (line_count + 1)
    else:
        print("ERROR: FILE \"" + file_dir + "\" does not exist.")
        exit()

Strangely, when I try calling the function it runs ok but the output is telling me that my file is 3 lines shorter than it actually is. When I print the file lines it appears to be skipping the last 3 lines of the file and I'm not sure why.

I have tested the below code using "with open" instead of read_file.seek.

Personal opinion but it works a lot better for reading .txt files. The function will return the number of lines found in the path given to the function. If it is not a file that exists it will error and exit.

def Get_Number_Lines(file_dir):
    exists = os.path.isfile(file_dir) 
    if (exists):
        print(file_dir)
        line_count = 0

        with open(file_dir, 'rb') as fin:

            reader = fin.readlines()

            for line in reader:
                line_count += 1

        return line_count

    else:
        print("ERROR: FILE \"" + file_dir + "\" does not exist.")
        exit()

Appreciate all the suggestions. So I discovered that I had a file object (in write mode) open prior to calling the get_number_lines() function ie

write_file = open(outputFileDir,"w+")
    # do stuff
get_number_lines(outputFileDir)

I then tried closing the the file prior to calling the function which solved the issue I was having. Out of curiousity I also tried this, which works no problem:

write_file = open(outputFileDir,"w+")
    # do stuff
write_file.close()
read_file.open(outputFileDir,"r")
get_number_lines(outputFileDir)

I didn't realise having two file objects (one in read, and one in write) could cause this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM