为什么会这样??将一个文本文件复制到另一个文本文件时出现?

2024-09-30 01:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

当我将一个文本文件复制到另一个文本文件时,新文件有两个字符:(??)在我不想要的结尾。你知道吗

我正在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如何创建文本文件。你知道吗


Tags: 文件thetotextfromtesttxtis
1条回答
网友
1楼 · 发布于 2024-09-30 01:35:08

Powershell正在使用UTF-16创建文件。您以文本模式(默认)打开了文件,但没有指定编码,因此python调用locale.getpreferredencoding(False)并使用该编码(在我的美国Windows系统上是cp1252)。你知道吗

文本模式转换行尾,使用错误的编码会产生问题。要解决此问题,请使用二进制模式获取字节对字节的副本,而不考虑编码。我还建议使用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)

相关问题 更多 >

    热门问题