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

时间:2010-04-15 00:55:14

标签: python windows newline

我想使用在Linux上运行的python编写带有DOS / Windows行结尾'\ r \ n'的文本文件。在我看来,必须有一个更好的方法,而不是手动在每行的末尾添加'\ r \ n'或使用行结束转换实用程序。理想情况下,我希望能够执行一些操作,例如将os.linesep分配给我在编写文件时要使用的分隔符。或者在我打开文件时指定行分隔符。

5 个答案:

答案 0 :(得分:72)

对于Python 2.6及更高版本,io模块中的open函数有一个可选的换行参数,可让您指定要使用的换行符。

例如:

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

答案 1 :(得分:3)

只需编写一个类似于文件的文件,然后在写入时将\n转换为\r\n

例如:

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

答案 2 :(得分:2)

您可以查看此PEP作为参考。

更新

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

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

答案 3 :(得分:1)

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

unix2windows /path/to/some/directory

它会忽略以“。”开头的文件夹中的文件。它还使用J.F.Sebastian在this answer中给出的方法忽略了它认为是二进制文件的文件。您可以使用可选的正则表达式位置参数进一步过滤:

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

这是完整的脚本。为避免疑义,我的部件根据the MIT licence许可。

#!/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))

答案 4 :(得分:0)

您可以编写一个转换文本然后编写它的函数。例如:

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