Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

python - Delete newline / return carriage in file output

I have a wordlist that contains returns to separate each new letter. Is there a way to programatically delete each of these returns using file I/O in Python?

Edit: I know how to manipulate strings to delete returns. I want to physically edit the file so that those returns are deleted.

I'm looking for something like this:

wfile = open("wordlist.txt", "r+")           
for line in wfile:
    if len(line) == 0:
        # note, the following is not real... this is what I'm aiming to achieve.
        wfile.delete(line)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> string = "testing
"
>>> string
'testing
'
>>> string = string[:-1]
>>> string
'testing'

This basically says "chop off the last thing in the string" The : is the "slice" operator. It would be a good idea to read up on how it works as it is very useful.

EDIT

I just read your updated question. I think I understand now. You have a file, like this:

aqua:test$ cat wordlist.txt 
Testing

This

Wordlist

With

Returns

Between

Lines

and you want to get rid of the empty lines. Instead of modifying the file while you're reading from it, create a new file that you can write the non-empty lines from the old file into, like so:

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

You should get:

aqua:test$ cat newwordlist.txt 
Testing
This
Wordlist
With
Returns
Between
Lines

If you want something like

TestingThisWordlistWithReturnsBetweenLines

just comment out

wf.write('
')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...