Python Forum
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)
Reply
#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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trouble with reading csv file and putting it into a file Milfredo 3 2,264 Sep-04-2020, 05:30 AM
Last Post: Milfredo
  Trouble reading Excel file. Shembeginner 2 2,294 Apr-07-2020, 04:55 AM
Last Post: Shembeginner
  python one line file processing har 4 3,248 Dec-09-2019, 06:10 AM
Last Post: har
  pdf file processing: how to "Enable Editing" Pavel_47 4 3,184 Dec-04-2019, 10:00 AM
Last Post: Pavel_47
  Error is wave file processing vipinv23 1 2,945 Jan-18-2019, 02:17 PM
Last Post: Larz60+
  Trouble importing text from a .docx file atinesh922 3 3,931 Jan-03-2018, 06:35 PM
Last Post: snippsat
  trouble writing to file after while loop Low_Ki_ 21 13,333 Jan-10-2017, 06:44 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020