2013-12-11 170 views
0

我刚刚写了几个月的pythonPython - 在文件输出中用换行/换行换行换行

Seconly,我有一个需要处理的txt文件。为了正确处理它,每行必须以'\ r \ n'结尾。

但是,情况并非总是如此,有时它包含'\ n'(换行符)。

因此,我需要检查文件,如果缺少'\ r \ n',请用'\ r \ n'替换'\ n'。

我尝试了几种方法并失败。

首先,我尝试了以下内容:

with open("initial_file.txt",'rb') as file_content: 
    #1253 is a Windows code page used to write modern Greek. 
    mycon = file_content.read().decode('cp1253') 

if (mycon.count("\r\n") == 0) and (mycon.count("\n") > 0): 
    with open("destination_file.txt",'w') as file_replace: 
    file_replace.write(mycon.replace("\n", "\r\n").encode('cp1253')) 

但不是与替换 '\ n' '\ r \ n' 我 '\ r \ r \ n'。

所以,我想另一种方法:

rf = open("initial_file.txt", 'rb') 
wf = open("destination_file.txt",'wb') 
mycon = rf.read().decode('cp1253') 
if (mycon.count('\r\n') == 0) and (mycon.count('\n') > 0): 
    for line in rf: 
     newline = line.rstrip('\n') 
     wf.write(newline).encode('cp1253') 
     wf.write('\r\n').encode('cp1253') 

它的工作的第一次,然后它没有。

我不知道我在做什么错,我可以欣赏一些帮助。

回答

2

您可以使用io module中的open功能。在那里你可以明确地指定换行模式。每'\n'转换为'\r\n'在这个例子:

from io import open 
with open("test.txt", "w+", newline="\r\n") as f: 
    f.write(u"Hello World\n") 

以下是文件内容(0d 0a相当于\r\n

$ hexdump -C test.txt 
00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 0d 0a   |Hello World..| 

对于现有的文件中使用特定的线路终端模式的转换,可以在利用universal newlines方法的同时读取这些行,然后可以使用明确指定的行结束符为输出文件编写行

from io import open 
with open(infname, 'r') as inf, open(outfname, "w+", newline="\r\n") as outf: 
    outf.writelines(inf) 

参考:

+0

谢谢,像魅力一样工作!我会确保阅读你所有的参考资料。 –

1

没有编码舞蹈,

with open("file.txt") as rf, open("out.txt", "w") as wf: 
    for line in rf: 
     wf.write("%s\r\n" % line.strip()) 

语境经理酷arn't他们。

+0

与我的fisrt代码示例相同的问题。出于某种原因,我无法理解它将'\ n'替换为'\ r \ r \ n' –

+0

如果您不确定该文件是否有回车符,则此答案有效。 – rjurney

0

您正在阅读的二进制模式的输入,但是写在文本模式输出。文本模式会自动将换行符转换为平台特定的换行符序列。由于CP1253与ascii和unicode具有相同的换行符和回车符,因此可以完全删除字符串替换代码和编码/解码代码。如果情况并非如此,那么您可能希望以二进制模式打开输出或进行其他更改。

with open("file.txt", 'rb') as rf, open("out.txt", "w") as wf: 
    wf.writelines(rf)