Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从txt文件中删除换行符的Python命令_Python - Fatal编程技术网

从txt文件中删除换行符的Python命令

从txt文件中删除换行符的Python命令,python,Python,我试图通过python从txt文件中删除文本行。我到处找,找到了很多答案,但还是找不到。到目前为止,我有: os.system("grep /n /home/pi/Documents/difference.txt >> /home/pi/grep1.txt") difference.txt包含以下内容: 192.168.0.*** 192.168.0.*** 192.168.0.*** 192.168.0.*** 我希望它看起来像这样: 192.168.0.*** 192.168

我试图通过python从txt文件中删除文本行。我到处找,找到了很多答案,但还是找不到。到目前为止,我有:

os.system("grep /n /home/pi/Documents/difference.txt >> /home/pi/grep1.txt")
difference.txt包含以下内容:

192.168.0.***
192.168.0.***
192.168.0.***
192.168.0.***
我希望它看起来像这样:

192.168.0.*** 192.168.0.*** 192.168.0.*** 192.168.0.***
但是grep1.txt是空的

抱歉,如果已经问过这个问题!:-

编辑
它可以是shell或python,我不在乎。

如果必须使用python,一种方法可能是:

with open('difference.txt', 'r') as f:
    c = f.read()

with open('grep1.txt', 'wb') as f:
    # python2.7
    # f.write(''.join(c).replace('\n', ' '))

    # in python3.x:
    f.write(bytes(''.join(c).replace('\n', ' '),  'utf-8'))
产生:

$ cat grep1.txt
192.168.0.*** 192.168.0.*** 192.168.0.*** 192.168.0.*** 
如果您想要一个unix工具,可以使用tr-translate字符:

cat difference.txt | tr '\n' '\0'

逐行读取文件并将它们连接在一起?这看起来更像是使用grep的问题,而不是Python的问题。/n是怎么回事?如果文件不是太大,请加载整个字符串,并对其调用replace来替换没有任何内容的行尾。我得到错误TypeError:需要一个类似字节的对象,而不是f.write'.joinc.replace'\n',“”您正在使用Python 3?将f.write参数强制转换为字节并编码。请参阅更新的答案