Jump to content
Sign in to follow this  
jarred33

Python File Read/Write

Recommended Posts

Using Python3- I am trying to read a file line by line and extract the distinct values between the 2nd and 3rd pipe ( | ) on all lines that start with a certain string (in this example, "TXA"). I know how to open and read the txt files line by line, and also know how to write to a new one. Not sure how to only write the values between the 2nd and 3rd pipe. The pipes are not always in the same spot, so I cant use a set index to print. Example of txt file and code are below.  Any help will be appreciated. 

 

distinct_value = []

with open ("textfile.txt",) as myfile:
    with open ('newtextfile.txt','w') as newfile:
        for lines in myfile:
                      if lines.startswith("TXA") and lines not in distinct_value:
                                distinct.append(lines)
                                newfile.writelines('\n'+lines)

 

 

 

textfile.txt example below.

 

ABC|asdf|111|111
TXA|SS2|234|222
TTT|SS3|1113|456|
TXA|SS45|3455|1111
PCS|222|45|SP333
TXA|344|34|3334
TXA|34445|3455|143111

 

 

newtextfile.txt would have the following values

234

3455

34

 

 

 

Share this post


Link to post
Share on other sites

Funce -  Thank you. This is just what I needed. Worked like a charm. 

 

 

distinct_value = []


with open ("MDMALL.txt",) as myfile:
    with open ("MDMADJUST.txt") as newfile:
        for lines in myfile:
                      if lines.startswith("TXA"):
                                distinct_value = lines.split("|")
                                print(distinct_value[5])

Share this post


Link to post
Share on other sites

Actually, I made another small adjustment to only get the distinct values. Thanks again. 

 

 

distinct_value = []


with open ("MDMALL.txt",) as myfile:
    with open ("MDMADJUST.txt",'w') as newfile:
        for lines in myfile:
                      if lines.startswith("TXA") and lines.split("|")[5] not in distinct_value:
                                distinct_value.append(lines.split("|")[5])
                                newfile.writelines(lines.split("|")[5])
                                newfile.writelines('\n')
                                
                                
print(*distinct_value, sep = '\n', end = '')

Edited by jarred33

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...