我想从包含字符串的用户那里获取输入,将该字符串存储到变量中,然后将其写入另一个字符串行中。
我尝试使用 open 和 .write 并使用 (%s( 将输入添加到写入的行中。
outF = open("file.txt", "w")
string = raw_input("enter string to add!")
outF.write('string data to write (%s)', % string)
outF.close()
试试这个:
outF = open("file.txt", "a") #append mode if u wish to add more data to the file later
string = raw_input("enter string to add!")
string_new="string u want to add before"+string #add strings wherever u need
outF.write(string_new)
outF.close()
看看这是否适合你
with open("file.txt", "r", encoding="utf-8") as file:
x = file.read()
with open("file.txt", "w", encoding="utf-8") as file:
print(x)
sentence = f"{x} {input('Add something: ')}. End."
file.write(sentence)