Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Trouble processing file
#1
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
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)
Quote
#2
import csv

with open('myFile.txt','r') as f:
    crdr = csv.reader(f, delimiter='|')
    for row in crdr:
        print(row)
Then process as list
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  python one line file processing har 4 284 Dec-09-2019, 06:10 AM
Last Post: har
  pdf file processing: how to "Enable Editing" Pavel_47 4 179 Dec-04-2019, 10:00 AM
Last Post: Pavel_47
  Error is wave file processing vipinv23 1 530 Jan-18-2019, 02:17 PM
Last Post: Larz60+
  Trouble importing text from a .docx file atinesh922 3 1,514 Jan-03-2018, 06:35 PM
Last Post: snippsat
  trouble writing to file after while loop Low_Ki_ 21 5,320 Jan-10-2017, 06:44 AM
Last Post: micseydel

Forum Jump:


Users browsing this thread: 1 Guest(s)