Python 使用终端写入不在Raspberry Pi中工作的文件
我会尽量简短 我刚得到一个树莓圆周率,我正试图用Python写一个文件。我写了一个小程序,从用户那里获取输入,并将其放入一个文本文件中Python 使用终端写入不在Raspberry Pi中工作的文件,python,raspberry-pi2,Python,Raspberry Pi2,我会尽量简短 我刚得到一个树莓圆周率,我正试图用Python写一个文件。我写了一个小程序,从用户那里获取输入,并将其放入一个文本文件中 # Grabs a line from user input and saves it to a file import sys for line in sys.stdin: file = open('notes.txt', 'a') file.write(line) file.close() 我试着在pythonshell中运行它,效果很
# Grabs a line from user input and saves it to a file
import sys
for line in sys.stdin:
file = open('notes.txt', 'a')
file.write(line)
file.close()
我试着在pythonshell中运行它,效果很好。但是,当我尝试在终端中使用python/python3test.py运行它时,它并没有起作用
我做错什么了吗?
谢谢期待您的光临
$ python notes.py <<< this is a bunch of stdin input that will be saved in notes.txt
这将提示输入您可以使用input/raw\u input如果您想从用户那里获取输入,您还应该在循环之外打开文件。我感觉第二个选项是OP想要的,有时您不知道您想要什么,直到有人告诉您;)谢谢,我用了原始输入。我使用了[code]虽然为True:line=raw_input()file=open('notes.txt','a')file.write(line+“\n”)file.close()[/code]@JaredFisher,您的while循环将永远不会结束,除非您结束脚本,否则您也不应该在循环内连续打开它。像Joran那样在外面打开一次。
with open("notes.txt","a") as f:
for line in iter(raw_input,""): #in py3 just use `input`
f.write(line+"\n")