Jul-30-2019, 03:01 AM
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.
MY DESIRED OUTPUT that should be written to a new file
Here is the actual code
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
field1|field2|field3\r\n
field1|field2|field3|field4|field5\r\n
\r\n
\r
string 1\r
\r\n
\r
string 2\r
\r\n
\r
string 3\r
field1|field2|field3|field4|field5\r\n
\r\n
\r
string 1\r
\r\n
\r
string 2\r
\r\n
\r
string 3\r
MY DESIRED OUTPUT that should be written to a new file
Quote:field1|field2|field3|||^
field1|field2|field3|||^
field1|field2|field3|field4|field5|
string 1
string 2
string 3^
field1|field2|field3|field4|field5|
string 1
string 2
string 3^
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)
