在linux上使用python编写DOS行结尾的文本文件

我想使用在Linux上运行的Python来编写带有DOS / Windows行末尾的文本文件“\ r \ n”。 在我看来,在每一行的末尾手动input'\ r \ n'或使用行结束转换实用程序必须有更好的方法。 理想情况下,我希望能够做一些事情,如分配给os.linesep我想在写入文件时使用的分隔符。 或者当我打开文件时指定行分隔符。

只要编写一个类似于其他文件的文件,并在写入时将\n转换为\r\n

例如:

 class ForcedCrLfFile(file): def write(self, s): super(ForcedCrLfFile, self).write(s.replace(r'\n', '\r\n')) 

对于Python 2.6和更高版本, io模块中的open函数具有可选的newline参数,可以指定要使用的新行。

例如:

 import io with io.open('tmpfile', 'w', newline='\r\n') as f: f.write(u'foo\nbar\nbaz\n') 

将创建一个包含这个文件:

 foo\r\n bar\r\n baz\r\n 

你可以看看这个PEP的一些参考。

更新:

@OP,你可以尝试创建这样的东西

 import sys plat={"win32":"\r\n", 'linux':"\n" } # add macos as well platform=sys.platform ... o.write( line + plat[platform] ) 

这是我写的一个python脚本。 它从给定的目录递归,用\ r \ n结尾替换所有\ n行尾。 像这样使用它:

 unix2windows /path/to/some/directory 

它忽略以'。'开头的文件夹中的文件。 它也忽略了它认为是二进制文件的文件,使用JF Sebastian在这个答案中给出的方法。 您可以使用可选的正则表达式位置参数进一步过滤:

 unix2windows /path/to/some/directory .py$ 

这是完整的脚本。 为了避免疑问,我的零件是根据MIT许可证授权的 。

 #!/usr/bin/python import sys import os import re from os.path import join textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f}) def is_binary_string(bytes): return bool(bytes.translate(None, textchars)) def is_binary_file(path): with open(path, 'rb') as f: return is_binary_string(f.read(1024)) def convert_file(path): if not is_binary_file(path): with open(path, 'r') as f: text = f.read() print path with open(path, 'wb') as f: f.write(text.replace('\r', '').replace('\n', '\r\n')) def convert_dir(root_path, pattern): for root, dirs, files in os.walk(root_path): for filename in files: if pattern.search(filename): path = join(root, filename) convert_file(path) # Don't walk hidden dirs for dir in list(dirs): if dir[0] == '.': dirs.remove(dir) args = sys.argv if len(args) <= 1 or len(args) > 3: print "This tool recursively converts files from Unix line endings to" print "Windows line endings" print "" print "USAGE: unix2windows.py PATH [REGEX]" print "Path: The directory to begin recursively searching from" print "Regex (optional): Only files matching this regex will be modified" print "" else: root_path = sys.argv[1] if len(args) == 3: pattern = sys.argv[2] else: pattern = r"." convert_dir(root_path, re.compile(pattern)) 

你可以编写一个函数来转换文本然后写入。 例如:

 def DOSwrite(f, text): t2 = text.replace('\n', '\r\n') f.write(t2) #example f = open('/path/to/file') DOSwrite(f, "line 1\nline 2") f.close()