gpt4 book ai didi

python - 如何在不引入回车的情况下在 Windows 上用 Python (3) 读/写文件?

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:38 26 4
gpt4 key购买 nike

我想在 Windows 上使用 Python 打开一个文件,执行一些正则表达式操作,可选择更改内容,然后将结果写回文件。

我可以创建一个看起来正确的示例文件(基于 SO 上其他帖子和文档中关于使用二进制模式的评论)。我看不到的是如何在不引入“\r”字符的情况下将“二进制”数据转换为可用形式。

一个例子:

import re

# Create an example file which represents the one I'm actually working on (a Jenkins config file if you're interested).
testFileName = 'testFile.txt'
with open(testFileName, 'wb') as output_file:
output_file.write(b'this\nis\na\ntest')

# Try and read the file in as I would in the script I was trying to write.
content = ""
with open(testFileName, 'rb') as content_file:
content = content_file.read()

# Do something to the content
exampleRegex = re.compile("a\\ntest")
content = exampleRegex.sub("a\\nworking\\ntest", content) # <-- Fails because it won't operate on 'binary data'

# Write the file back to disk and then realise, frustratingly that something in this process has introduced carriage returns onto every line.
outputFilename = 'output_'+testFileName
with open(outputFilename, 'wb') as output_file:
output_file.write(content)

最佳答案

我猜你的意思是,你的文本文件有回车符,你不希望它们包含在文本中。

如果你使用 以 open(fileName, 'r', encoding="utf-8", errors="ignore", newline="\r\n") 作为内容文件

或者更具体地说,在你的 open 调用中设置 newline="\r\n",它应该在新行上消耗回车符。

编辑:或者如果您只想对 \n 进行操作,那么这个工作示例应该可以做到。

import re

testFileName = 'testFile.txt'
with open(testFileName, 'w', newline='\n') as output_file:
output_file.write('this\nis\na\ntest')

content = ""
with open(testFileName, 'r', newline='\n') as content_file:
content = content_file.read()

exampleRegex = re.compile("a\\ntest")
content = exampleRegex.sub("a\\nworking\\ntest", content)

outputFilename = 'output_'+testFileName
with open(outputFilename, 'w', newline='\n') as output_file:
output_file.write(content)

关于python - 如何在不引入回车的情况下在 Windows 上用 Python (3) 读/写文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32567445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com