windows 在Linux下用python编写以DOS行结尾的文本文件

kdfy810k  于 7个月前  发布在  Windows
关注(0)|答案(6)|浏览(94)

我想使用运行在Linux上的python编写DOS/Windows行结尾为“\r\n”的文本文件。在我看来,一定有比手动将"\r\“n'在每一行的末尾或使用一个行结束转换工具。理想情况下,我希望能够做一些事情,如分配给os.linesep分隔符,我想在编写文件时使用。或指定行分隔符当我打开文件。

c3frrgcw

c3frrgcw1#

对于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

brccelvz

brccelvz2#

你可以参考一下这个PEP
更新:
@OP,你可以尝试创建这样的东西

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

字符串

z4bn682m

z4bn682m3#

只需编写一个file-like,它 Package 另一个file-like,并在写入时将\n转换为\r\n
举例来说:

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

字符串

hmtdttj4

hmtdttj44#

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

unix2windows /path/to/some/directory

字符串
它忽略文件夹中以“.”开头的文件。它还忽略它认为是二进制文件的文件,使用J.F.塞巴斯蒂安在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))

vnzz0bqm

vnzz0bqm5#

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

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

字符串

am46iovg

am46iovg6#

如果你碰巧在Pandas中通过to_csv()函数编写你的.txt文件,你可以像the documentation中讨论的那样添加参数lineterminator = '\r\n'
范例:
df.to_csv('file_with_line_endings.txt', lineterminator = '\r\n')

相关问题