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

问题描述 投票:0回答:6

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

python windows newline
6个回答
93
投票

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

2
投票

您可以看看这个PEP以供参考。

更新:

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

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

1
投票

只需编写一个类似文件,包装另一个类似文件,并在写入时将

\n
转换为
\r\n

例如:

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

1
投票

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

unix2windows /path/to/some/directory

它会忽略以“.”开头的文件夹中的文件。它还使用 J.F. Sebastian 在“这个答案”中给出的方法忽略它认为是二进制文件的文件。您可以使用可选的正则表达式位置参数进一步过滤: unix2windows /path/to/some/directory .py$

这是完整的脚本。为避免疑义,我的部件已获得
麻省理工学院许可证

的许可。 #!/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))



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



0
投票
lineterminator = '\r\n'

,如

文档
中所述。

© www.soinside.com 2019 - 2024. All rights reserved.