我的代码看起来像这样:
def storescores():
hs = open("hst.txt","a")
hs.write(name)
hs.close()
Run Code Online (Sandbox Code Playgroud)
因此,如果我运行它并输入"Ryan"然后再次运行它并输入"Bob"文件hst.txt看起来像
RyanBob
Run Code Online (Sandbox Code Playgroud)
代替
Ryan
Bob
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
我有多个(40到50个)MP3文件,我想连接成一个文件.在Python中执行此操作的最佳方法是什么?
with open("games.txt", "w") as text_file:
print(driver.current_url)
text_file.write(driver.current_url + "\n")
Run Code Online (Sandbox Code Playgroud)
我现在正在使用此代码,但是当它写入文件时,它会覆盖旧内容.如何在不删除已经存在的内容的情况下简单地添加它.
可能重复:
Python - 何时使用文件vs打开
从官方python文档,
http://docs.python.org/library/functions.html#file
打开文件时,最好使用open()而不是直接调用此构造函数
但它没有给出理由.
下面的代码是我到目前为止的代码.当它写入.csv时,它会覆盖我之前在文件中写入的内容.如何以不擦除我之前文本的方式写入文件.(我的代码的目标是拥有一个人输入他们的名字并让程序记住它们)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
Run Code Online (Sandbox Code Playgroud) 我知道如何创建文件,但在这种情况下,它会覆盖所有数据:
import io
with open('text.txt', 'w', encoding='utf-8') as file:
file.write('text!')
Run Code Online (Sandbox Code Playgroud)
在*nix我可以做的事情:
#!/bin/sh
if [ -f text.txt ]
#If the file exists - append text
then echo 'text' >> text.txt;
#If the file doesn't exist - create it
else echo 'text' > text.txt;
fi;
Run Code Online (Sandbox Code Playgroud) file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
....(Somewhere else in the code)
file = io.open('spam.txt', 'w')
file.write(u'Spam and eggs!\n')
file.close()
Run Code Online (Sandbox Code Playgroud)
我想知道如何保存我可以写入的log.txt文件?我希望能够打开一个txt文件,写入它,然后能够稍后打开它并让前一次写入的内容仍然存在.
我正在开发一个将行写入CSV的应用程序.但是,当我第二次运行应用程序时,已经写入的行将被新行覆盖.我怎样才能使作者写入下一个空白行,而不是已经有数据的空白行?我还没有找到任何关于如何做到这一点.这是我的代码如下:
listsof = [1, 2, 3, 4]
with open('C:/Users/Family3/Downloads/weather.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(listsof)
Run Code Online (Sandbox Code Playgroud) 您好,我有一个 git 文件,我不希望将更改合并到其中,相反,我希望更改始终附加到文件末尾,而其余项目文件正常合并。这可以在 git 中配置吗?
例如,在上游,文件 F 有一行
1. |10-09-2016 00:12:43 : Check completed
Run Code Online (Sandbox Code Playgroud)
在我的 fork 中,我将 F 更改为
1. |11-09-2016 00:10:55 : Check completed
Run Code Online (Sandbox Code Playgroud)
然后我提交更改并创建从我的分支到上游的 MR。
而不是将 upsteam 上的文件 F 更改为
1. |11-09-2016 00:10:55 : Check completed
Run Code Online (Sandbox Code Playgroud)
我希望upsteam上的文件F在接受MR后变成
1. |10-09-2016 00:12:43 : Check completed
2. |11-09-2016 00:10:55 : Check completed
Run Code Online (Sandbox Code Playgroud) 我目前正在编写一些需要我记录结果的代码。但是,目前,我使用的代码只是覆盖了文档,而不是添加。我可以写什么来在文本文档的末尾添加一些东西?