Home > Net >  Replace text and emty lines in txt file
Replace text and emty lines in txt file

Time:01-28

Whant to replace "|" whit ";" and remove emty lines in a txt file and save as csv

My code so far The replacement works but not remove emty lines. And it save same line twice in csv

f1 = open("txtfile.txt", 'r ')
f2 = open("csvfile.csv", 'w')
for line in f1:
    f2.write(line.replace('|', ';'))
    if line.strip():
        f2.write(line)
        print(line)

 
        
    
f1.close()
f2.close()

CodePudding user response:

In your code, f2.write(line.replace('|', ';')) converts line by replacing the | to ; and writes to csv file without checkng emptiness. So you are getting empty lines in csv file. Again in the if condition, f2.write(line) writes the original line once more. That is why you are getting same line (well almost) twice.

Instead of writing the modified line to file, save the it to line like -

for line in f1:
    line = line.replace('|', ';')
    if line.strip():
        f2.write(line)

Here we are first modifying the line to change | to ; and overwrite line with the modified content. Then it checks for emptiness and writes in the csv file. So, the line is printed once and empty lines are skipped.

for line in f1:
    if line.strip(): # Check emptiness first
        f2.write(line.replace('|', ';')) # then directly write modified line
  • Related