简体   繁体   English

写入python中文件的最后一行

[英]Write to last line of file in python

I wanna save some string on a file that i called inv.data. 我想在我称为inv.data的文件中保存一些字符串。 Every time i write a special command, I want to save a string in the file. 每次我写一个特殊命令时,我都想在文件中保存一个字符串。 The string should be at the last line in the file all times. 该字符串应始终位于文件的最后一行。 I read something about append, so I tried to do something like this: 我阅读了一些有关append的内容,因此我尝试执行以下操作:

#Open and close the inventroy file
fileOpen = open('inv.data', 'a')
fileOpen.write(argOne)
fileOpen.close()

fileOpen = open('inv.data', 'r')
savedData = fileOpen.read().splitlines()
fileOpen.close()

This works fine the first time I want to add something during runtime, but when I try to add the second string it looks something like this: 第一次我想在运行时添加一些东西时,这种方法可以正常工作,但是当我尝试添加第二个字符串时,它看起来像这样:

sword
axe
shield
bow
flower
monsterLol

Where monster was the first add, and Lol was the second thing I added. 我首先添加了Monster,而Lol是第二添加。 What am I missing? 我想念什么? Do I need to specify that it should go to a new line each time or? 我是否需要指定它应该每次都换行?

New line is not getting added and hence the next entry is appended in the same line. 没有添加新行,因此下一个条目将添加到同一行中。 You ca rectify this as follows: 您可以按照以下说明进行纠正:

fileOpen.write(argOne + '\n')

This way you don't have to modify the way you input your arguments. 这样,您不必修改输入参数的方式。

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

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