使用 Python3 以 ASCII 格式写入文件,而不是 UTF8

Cig*_*acs 2 unicode utf-8 python-3.x

我有一个由两个部分创建的程序。

\n\n

第一个以这种格式复制一个文件名中间有一个整数的文本文件。

\n\n
file = "Filename" + "str(int)" + ".txt" \n
Run Code Online (Sandbox Code Playgroud)\n\n

用户可以创建任意数量的文件副本。

\n\n

该程序的第二部分是我遇到的问题。文件的最底部有一个整数,与文件名中的整数相对应。第一部分完成后,我以读/写格式一次打开每个文件"r+"。这样我就可以file.seek(1000)知道整数在文件中的位置。

\n\n

现在我认为下一部分应该很容易。我只需要将 str(int) 写入此处的文件即可。但这并不那么容易。在家里的 Linux 中这样做效果很好,但在 Windows 上工作却很困难。我最终要做的file.seek(1000)就是使用 Unicode UTF-8 写入文件。我用程序其余部分的代码片段完成了这一点。我会将其记录下来,以便能够理解正在发生的事情。我希望能够用老式的常规英文 ASCII 字符来编写,而不是用 Unicode 来编写。最终这个程序将被扩展以在每个文件的底部包含更多的数据。必须以 Unicode 格式写入数据将使事情变得极其困难。如果我只是写入数据而不将其转换为 Unicode,这就是结果。该字符串应该说#2 =1534,但它说#2 =\xe3\x84\xa0\xe3\x8c\xb5433.

\n\n

如果有人可以告诉我我做错了什么,那就太好了。我希望只使用类似file.write(\'1534\')将数据写入文件的方法,而不必使用 Unicode UTF-8 进行操作。

\n\n
while a1 < d1 :\n    file = "file" + str(a1) + ".par"\n    f = open(file, "r+")\n    f.seek(1011)\n    data = f.read()  #reads the data from that point in the file into a variable.\n    numList= list(str(a1)) # "a1" is the integer in the file name. I had to turn the integer into a list to accomplish the next task.\n    replaceData = \'\\x00\' + numList[0] + \'\\x00\' + numList[1] + \'\\x00\' + numList[2] + \'\\x00\' + numList[3] + \'\\x00\' #This line turns the integer into Utf 8 Unicode. I am by no means a Unicode expert.\n    currentData = data #probably didn\'t need to be done now that I\'m looking at this.\n    data = data.replace(currentData, replaceData) #replaces the Utf 8 string in the "data" variable with the new Utf 8 string in "replaceData."\n    f.seek(1011) # Return to where I need to be in the file to write the data.\n    f.write(data) # Write the new Unicode data to the file\n    f.close() #close the file\n    f.close() #make sure the file is closed (sometimes it seems that this fails in Windows.)\n    a1 += 1 #advances the integer, and then return to the top of the loop\n
Run Code Online (Sandbox Code Playgroud)\n

Eva*_*van 8

这是用 ASCII 写入文件的示例。您需要以字节模式打开文件,并且对字符串使用 .encode 方法是获得所需最终结果的便捷方法。

s = '12345'
ascii = s.encode('ascii')
with open('somefile', 'wb') as f:
    f.write(ascii)
Run Code Online (Sandbox Code Playgroud)

如果文件已经存在,您显然也可以在您的情况下以 rb+ (读写字节模式)打开。

with open('somefile', 'rb+') as f:
    existing = f.read()
    f.write(b'ascii without encoding!')
Run Code Online (Sandbox Code Playgroud)

您还可以只传递带有 b 前缀的字符串文字,它们将使用 ascii 进行编码,如第二个示例所示。