简体   繁体   中英

Remove line character from a text file using Python (With a condition)

I am new to Stack Overflow site and Python too.

I have a text file which contains transaction of a company with pipe delimiter

There are certain transactions which comes on the second line due to line character.These transactions typically have one more line character in the second line too.

i want to bring the second line and concatenate it with the first line using python.

A sample file given below for my friends to facilitate understanding my issue (Line Numbers are just for our reference purposes):

Line1: A|B|C|D Line2: A|B|C| Line3: D Line4: Line5: A|B Line6: C|D Line7: Line8: A|B|C|D

Thanks alot for reading this and for providing the solution.

while line in fin:
    if line.strip().endswith('|'):
        fou.write(line.strip())
    else:
        fou.write(line)

This simple code will do. Assuming fin, fou are input and output files you've opened.

If a line ends with '|' , new line will be written after strip() method which will erase \\n or any spacing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM