删除文件输出中的换行符/返回载体 [英] Delete newline / return carriage in file output

查看:79
本文介绍了删除文件输出中的换行符/返回载体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单词列表,其中包含用于分隔每个新字母的返回。有没有办法在Python中使用文件I / O以编程方式删除每个返回?

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?

编辑:我知道如何操纵字符串来删除返回。我想物理编辑文件,以便删除这些返回。

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)


推荐答案

>>> string = "testing\n"
>>> string
'testing\n'
>>> 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.

编辑

我刚看了你更新的问题。我想我现在明白了。你有一个文件,如下所示:

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('\r\n')
    wf.write(newline)
    wf.write('\n')  # remove to leave out line breaks
rf.close()
wf.close()

你应该得到:

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

如果你想要像

TestingThisWordlistWithReturnsBetweenLines

只需注释

wf.write('\n')

这篇关于删除文件输出中的换行符/返回载体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆