Home > Blockchain >  How do I get Python to starting reading a file on the first line?
How do I get Python to starting reading a file on the first line?

Time:09-23

I am trying to read through a log that contains a list of files that caused errors, identify the filenames, and print the fullpath to those files. There is one file per line and it has particular formatting to delimit information of different types, so I am looking to stop reading at the first instance of a "." character in each line (none of the files have extensions). It works exactly as intended... except that it always begins at the second line of the error list and ends one past the last line, so it skips the first file. To me this seems like an indexing error, but I can't see what I've indexed incorrectly.

errorList = "path/to/listoferrors"
PART = ""
partCounter = 0
currentChar = ""

with open(errorList, "r") as file: #opens list of errors
    for line in file:              
        for char in line:          
            currentChar = file.read(1)
            if((currentChar != ".") and (partCounter == 0)): #check if we've reached the end of the PART
                PART = PART   currentChar

The above is the start of the code. It builds the filename character by character until it gets to the period. I'm fairly new to python, can anyone tell me what I'm doing wrong and how to get it to start on the first line of the file?

CodePudding user response:

for line in file:

reads the file line by line. So it reads the first line of the file on the first iteration.

Then when you do currentChar = file.read(1), it starts reading from where the for loop left off, which is the beginning of the second line. That's why you're skipping the first line.

If you want to read until the first . in each line, use line.index('.') to find that position, and slice the line.

for line in file:
    dot = line.index('.')
    if dot != -1:
        part = line[:dot]
  • Related