从文件中读取然后再写出来,我得到了汉字

Di *_*Zou 4 python python-2.7

我正在读取文件中的所有行,然后再将它们写出来.当我这样做时,我写的文件最终主要是中文字符.我根本没有修改任何行.这是我的Python代码:

#test.py
import os, sys, time
import getopt

if __name__=='__main__':
    testFile = None
    try:
        optlist, args = getopt.getopt(sys.argv[1:],"",["file="])
    except Exception, e:
        print e
        sys.exit(1)
    for opt, arg in optlist:
        if opt == '--file':
            testFile = arg.strip()

    print testFile
    if os.path.isfile(testFile):
        f = open(testFile, 'r')
        lines = f.readlines()
        f.close()
        f = open(testFile, 'w')
        for line in lines:
            f.write(line)
        f.close()
Run Code Online (Sandbox Code Playgroud)

这是我正在测试此代码的原始文件:

param($Identity = "")


if($_INITIALIZATION_isLoaded -ne $true){
    #load initialization script
    . ((split-path -parent $myInvocation.InvocationName) + "\stuff.ps1")
}
Run Code Online (Sandbox Code Playgroud)

写完文件后,这是文件的内容:

param($Identity = "")

???

??????????????????????????????????????????? #load initialization script

????????????????????????????????????????????????????????????????????????}
Run Code Online (Sandbox Code Playgroud)

我运行Python脚本的命令行语句是:

python test.py --file="test.txt"
Run Code Online (Sandbox Code Playgroud)

我在Windows 7上使用Python 2.7进行此操作.导致此问题的原因是什么以及如何解决?谢谢.

编辑:

如果我print lines在我的脚本中添加一个,我得到这个:

['\xfe\xff\x00p\x00a\x00r\x00a\x00m\x00(\x00$\x00I\x00d\x00e\x00n\x00t\x00i\x00t\x00y\x00 \x00=\x00 \x00"\x00"\x00)\x00\r\x00\n', '\x00\r\x00\n', '\x00\r\x00\n'
, '\x00i\x00f\x00(\x00$\x00_\x00I\x00N\x00I\x00T\x00I\x00A\x00L\x00I\x00Z\x00A\x00T\x00I\x00O\x00N\x00_\x00i\x00s\x00L\x00o\x00a\x00d\x00e\x00d\x00 \x00-\x00n\x
00e\x00 \x00$\x00t\x00r\x00u\x00e\x00)\x00{\x00\r\x00\n', '\x00\t\x00#\x00l\x00o\x00a\x00d\x00 \x00i\x00n\x00i\x00t\x00i\x00a\x00l\x00i\x00z\x00a\x00t\x00i\x00o
\x00n\x00 \x00s\x00c\x00r\x00i\x00p\x00t\x00\r\x00\n', '\x00\t\x00.\x00 \x00(\x00(\x00s\x00p\x00l\x00i\x00t\x00-\x00p\x00a\x00t\x00h\x00 \x00-\x00p\x00a\x00r\x0
0e\x00n\x00t\x00 \x00$\x00m\x00y\x00I\x00n\x00v\x00o\x00c\x00a\x00t\x00i\x00o\x00n\x00.\x00I\x00n\x00v\x00o\x00c\x00a\x00t\x00i\x00o\x00n\x00N\x00a\x00m\x00e\x0
0)\x00 \x00+\x00 \x00"\x00\\\x00s\x00t\x00u\x00f\x00f\x00.\x00p\x00s\x001\x00"\x00)\x00\r\x00\n', '\x00}\x00\r\x00\n']
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 13

您的原始文件是UTF-16,并且某个字节已被丢弃,导致所有字符都被一个字节关闭.

$ charinfo "????"
U+4900 CJK UNIFIED IDEOGRAPH-4900
U+4E00 CJK UNIFIED IDEOGRAPH-4E00
U+4900 CJK UNIFIED IDEOGRAPH-4900
U+5400 CJK UNIFIED IDEOGRAPH-5400
$ charinfo "INIT"
U+0049 LATIN CAPITAL LETTER I
U+004E LATIN CAPITAL LETTER N
U+0049 LATIN CAPITAL LETTER I
U+0054 LATIN CAPITAL LETTER T
Run Code Online (Sandbox Code Playgroud)

考虑使用codecs.open()它以处理转码问题.