python - Delete newline / return carriage in file output -


i have wordlist contains returns separate each new letter. there way programatically delete each of these returns using file i/o in python?

edit: know how manipulate strings delete returns. want physically edit file returns deleted.

i'm looking this:

wfile = open("wordlist.txt", "r+")            line in wfile:     if len(line) == 0:         # note, following not real... i'm aiming achieve.         wfile.delete(line) 

>>> string = "testing\n" >>> string 'testing\n' >>> string = string[:-1] >>> string 'testing' 

this says "chop off last thing in string" : "slice" operator. idea read on how works very useful.

edit

i read updated question. think understand now. have file, this:

aqua:test$ cat wordlist.txt  testing   wordlist   returns  between  lines 

and want rid of empty lines. instead of modifying file while you're reading it, create new file can write non-empty lines old file into, so:

# script     rf = open("wordlist.txt") wf = open("newwordlist.txt","w") line in rf:     newline = line.rstrip('\r\n')     wf.write(newline)     wf.write('\n')  # remove leave out line breaks rf.close() wf.close() 

you should get:

aqua:test$ cat newwordlist.txt  testing wordlist returns between lines 

if want like

testingthiswordlistwithreturnsbetweenlines 

just comment out

wf.write('\n') 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -