在文件输出中删除换行符/回车 [英] Delete newline / return carriage in file output

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

问题描述

我有一个单词表,其中包含用于分隔每个新字母的回车符.有没有办法在 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
"
>>> 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.

编辑

我刚刚阅读了您更新的问题.我想我现在明白了.您有一个文件,如下所示:

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()

你应该得到:

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

如果你想要类似的东西

TestingThisWordlistWithReturnsBetweenLines

注释掉

wf.write('
')

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

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