简体   繁体   中英

Python not reading the first line of my file

I have a homework assignment where the goal is to count the number of times certain words occur in a file, however when I open the file I cannot get it to read the first line of said file.

while True:
    try:
        File_Name = input("Enter file name ")
        with open(File_Name, "r") as File:
            print("File opened")
            for line in File:
                text = File.read()
                print("File Read")
                replaced = text.replace(".", " ").replace(","," ").replace("!", " ").replace("?", " ").replace(":", " ").replace(";", " ").lower()
                print("File edited")
                print(replaced)      
    except:
        print("Invalid File Name, please retry")
        continue```

This is the text I am using just for testing:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
inciDiDunt uT labOre et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure 
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

And this is the output I get:

File opened
File Read
File edited
incididunt ut labore et dolore magna aliqua  ut enim ad minim veniam  quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat  duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur
excepteur sint occaecat cupidatat non proident  sunt in culpa qui officia deserunt mollit anim id est laborum ```

You are mixing and matching consumption modes. You should stop that.

    with open(File_Name, "r") as File:
        print("File opened")
        for line in File:
            text = File.read()

This block of code:

  1. Opens the file.
  2. Prepares to consume the file line by line ( for line in File: ).
  3. Consumes all remaining content in a single go ( text = File.read() ).

You should either:

  1. Consume the file line by line (remove the File.read() )
  2. Consume the entire file (remove the unnecessary for loop).

Your for line in File actually read the first line of the file.

So at the first iteration, the first line of your file is stored in the line variable, and text = File.read() reads the rest

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