Trouble processing file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Trouble processing file (/thread-20154.html) |
Trouble processing file - villumanati - Jul-30-2019 Hello I am new to python and am attempting to read a text file. The file is of the below format. Note the \r represents carriage return. \n represents a new line. These aren't actually present in the file unless I turn on "view line endings" on on my text editor Would someone tell me what is the best approach to get this file read? I am attempting to read the file and do some other manipulation to each line of data that was read in then write to a new file. I seem to be making a mistake on the line with 5 fields. I can read the first 2 rows easily, but the program stops when it gets to the third line. Quote:field1|field2|field3\r\n MY DESIRED OUTPUT that should be written to a new file Quote:field1|field2|field3|||^ Here is the actual code with open('myFile.txt','r') as f: line = f.readlines(1); while line: line = f.readlines(1) if not line: print('List is empty') continue else: numofPipes = line[0].count('|') if numofPipes == 95: newOutput = line[0].rstrip('\r').rstrip('\n') + '|||||||||^' print(newOutput) elif numofPipes == 103: newOutput = line[0].rstrip('\r').rstrip('\n') + '|' # finish inserting code to continue to read lines until condition met reportText = f.realines(1) print(newOutput) RE: Trouble processing file - Larz60+ - Jul-30-2019 import csv with open('myFile.txt','r') as f: crdr = csv.reader(f, delimiter='|') for row in crdr: print(row)Then process as list |