如何将LF转换为CRLF?

Rus*_*hal 9 python unix

我在网上找到了大多数英文单词的列表,但换行符是unix-style(用Unicode编码:UTF-8).我在这个网站上找到了它:http://dreamsteep.com/projects/the-english-open-word-list.html

如何将换行符转换为CRLF,以便我可以迭代它们?我将使用它们的程序遍历文件中的每一行,因此每行必须有一个单词.

这是文件的一部分: bitbackbitebackbiterbackbitersbackbitesbackbitingbackbittenbackboard

它应该是:

bit
backbite
backbiter
backbiters
backbites
backbiting
backbitten
backboard
Run Code Online (Sandbox Code Playgroud)

如何将文件转换为此类型?注意:它是26个文件(每个字母一个),总共80,000个单词(所以程序应该非常快).

我不知道从哪里开始,因为我从未使用过unicode.提前致谢!

使用rU作为参数(如建议的那样),在我的代码中使用:

with open(my_file_name, 'rU') as my_file:
    for line in my_file:
        new_words.append(str(line))
my_file.close()
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    addWords('B Words')
  File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\hangman.py", line 138, in addWords
    for line in my_file:
  File "C:\Python3.3\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 7488: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)

谁能帮我这个?

NPE*_*NPE 18

您应该能够使用Python的通用换行支持打开文件,而不是转换:

f = open('words.txt', 'rU')
Run Code Online (Sandbox Code Playgroud)

(注意U.)

  • 现在似乎已弃用:https://docs.python.org/3.6/library/functions.html#open (2认同)

dug*_*res 13

您可以使用字符串的replace方法.喜欢

txt.replace('\n', '\r\n')
Run Code Online (Sandbox Code Playgroud)

编辑:
在你的情况下:

with open('input.txt') as inp, open('output.txt', 'w') as out:
    txt = inp.read()
    txt = txt.replace('\n', '\r\n')
    out.write(txt)
Run Code Online (Sandbox Code Playgroud)