gpt4 book ai didi

python - 为什么 ??当我将一个文本文件复制到另一个文本文件时出现?

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:25 25 4
gpt4 key购买 nike

当我将一个文本文件复制到另一个文本文件时,新文件的末尾有两个字符:(??),这是我不想要的。

我在Windows7上使用的是Python3.6.0

这是我的脚本:

from sys import argv
script, from_file, to_file = argv

#Open from_file and get the text from it
indata = open(from_file).read()

#Write the from_file text to to_file
open(to_file, 'w').write(indata)

我在 PowerShell 中运行以下命令:

>echo "This is a test file." > TestSource.txt
>type TestSource.txt
This is a test file.
>python CopyFile.py TestSource.txt TestDestination.txt
>type TestDestination.txt
This is a test file.??

为什么我创建的文件中出现两个问号(??)?

编辑:This Related Question被建议为重复。我的问题是关于将一​​个文本文件复制到另一个文本文件时 Python 的行为方式。这个相关问题是关于 Windows PowerShell 如何创建文本文件的。

最佳答案

Powershell 正在使用 UTF-16 创建文件。您已在未指定编码的情况下以文本模式(默认)打开文件,因此 python 调用 locale.getpreferredencoding(False) 并使用该编码(cp1252 在我的美国 Windows 系统上).

文本模式翻译行尾,使用错误的编码会产生问题。要解决此问题,请使用二进制模式来获取字节对字节的副本,而不管编码如何。我还建议使用 with 来确保文件正确关闭:

from sys import argv
script, from_file, to_file = argv

#Open from_file and get the text from it
with open(from_file,'rb') as f:
data = f.read()

#Write the from_file text to to_file
with open(to_file,'wb') as f:
f.write(data)

关于python - 为什么 ??当我将一个文本文件复制到另一个文本文件时出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976302/

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