简体   繁体   English

附加文本文件

[英]Appending a text file

I'm teaching myself how to program and am currently using Python 3.3. 我正在教自己如何编程,目前正在使用Python 3.3。 I'm trying to append a text file. 我正在尝试附加文本文件。 Currently, the text file looks like: 当前,该文本文件如下所示:

117: 5.21|8.50|10.0|3.42

This text is keeping track of ratings. 该文本跟踪收视率。 So ITEM_A has been rated 117 times, characteristic 1 has an average rating of 5.21, characteristic 2 has an average rating of 8.50, characteristic 3 has an average rating of 10.0 and so on... 因此,ITEM_A的评级为117次,特征1的平均评级为5.21,特征2的平均评级为8.50,特征3的平均评级为10.0,依此类推...

I wish to be able to update these. 我希望能够更新这些。 So if I wish to rate ITEM_A again, 117 changes to 118, and the scores 4.20|7.50|6.33|9.05 will also change to reflect the updated averages. 因此,如果我希望再次对ITEM_A评分,则117会变为118,并且得分4.20|7.50|6.33|9.05也将改变以反映更新的平均值。

I thought I could do this while in the append/read access mode ('a+') using a combination of tell() , seek() and write() . 我以为我可以在Tell / seek()write()的组合的追加/读取访问模式('a +')中执行此操作。 However, I seem to only be able to write to the end of my file. 但是,我似乎只能写到文件末尾。 Am I barking up the wrong tree, or is my code just incorrect? 我是不是树错了树,还是我的代码不正确?

test_file = 'example.txt'           #Current:   117: 5.21|8.50|10.0|3.42
file = open(test_file, 'a+')

file.seek(0, 0)
file.write('118')                    #I want:   118: 5.21|8.50|10.0|3.42

file.close()

The docs ( http://docs.python.org/3.3/library/functions.html#open ) say that docs( http://docs.python.org/3.3/library/functions.html#open )说

'a' is for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). 'a'用于追加(在某些Unix系统上,意味着所有写入均追加到文件的末尾,而不管当前查找位置如何)。

I think you want the 'r+' mode..? 我认为您要使用'r+'模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM