首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python3而不是UTF8写入ASCII码文件

使用Python3而不是UTF8写入ASCII码文件
EN

Stack Overflow用户
提问于 2017-10-20 21:26:08
回答 1查看 12.6K关注 0票数 1

我有一个程序,我创建了两个部分。

第一个方法复制一个文本文件,文件名中间有一个整数,格式如下。

代码语言:javascript
复制
file = "Filename" + "str(int)" + ".txt" 

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

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

现在,在我看来,下一部分应该很简单。我应该只需要在这里将str(int)写入文件中。但这并不是那么简单。在家中像在Linux上那样工作很好,但在Windows上工作证明是困难的。在file.seek(1000)之后,我最终必须做的是使用Unicode UTF-8写入文件。我用程序其余部分的代码片段实现了这一点。我会将其记录下来,以便能够理解正在发生的事情。与其用Unicode写这篇文章,我倒希望能用古老的英文ASCII字符来写这篇文章。最终,该程序将扩展为在每个文件的底部包含更多数据。必须用Unicode编写数据将使事情变得极其困难。如果我只是写数据,而不把它转换成Unicode,这就是结果。此字符串应该是#2 =1534,而不是#2 =ㄠ㌵433.

如果有人能告诉我我做错了什么,那就太好了。我喜欢使用像file.write('1534')这样的东西将数据写到文件中,而不是使用Unicode UTF-8。

代码语言:javascript
复制
while a1 < d1 :
    file = "file" + str(a1) + ".par"
    f = open(file, "r+")
    f.seek(1011)
    data = f.read()  #reads the data from that point in the file into a variable.
    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.
    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.
    currentData = data #probably didn't need to be done now that I'm looking at this.
    data = data.replace(currentData, replaceData) #replaces the Utf 8 string in the "data" variable with the new Utf 8 string in "replaceData."
    f.seek(1011) # Return to where I need to be in the file to write the data.
    f.write(data) # Write the new Unicode data to the file
    f.close() #close the file
    f.close() #make sure the file is closed (sometimes it seems that this fails in Windows.)
    a1 += 1 #advances the integer, and then return to the top of the loop
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-20 21:38:20

这是一个在ASCII中写入文件的示例。您需要以字节模式打开文件,使用字符串的.encode方法可以方便地获得所需的最终结果。

代码语言:javascript
复制
s = '12345'
ascii = s.encode('ascii')
with open('somefile', 'wb') as f:
    f.write(ascii)

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

代码语言:javascript
复制
with open('somefile', 'rb+') as f:
    existing = f.read()
    f.write(b'ascii without encoding!')

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46850103

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档