简体   繁体   English

Python用户输入文件名

[英]Python User Input File Name

I'm trying to write a program that takes a users input for a file name, and then either opens the file to add to it, or prints what is already in the file, so far this is what I have: (I keep getting a syntax error where it tries to print 'file name' is now open) any ideas/tips? 我正在尝试编写一个程序,该程序需要用户输入文件名,然后打开文件以添加到文件中,或者打印文件中已存在的文件,到目前为止,这就是我所拥有的:(我一直在尝试打印“文件名”的语法错误已打开)有任何想法/提示吗?

            elif choice == 'a':
                print("You selected 'a', you can now add to your file.")
                print("File", ui "is now open.")

You are having the following print statement in your elif block 您的elif块中包含以下print语句

print("File", ui "is now open.")

which is syntactically wrong, since it doesn't have a comma after ui , and you can't concatenate or perform any other operation thus. 从语法上讲这是错误的,因为ui之后没有逗号,因此您无法连接或执行任何其他操作。

Either of the following should correct that 以下任一情况均应纠正该问题

print("File", ui, "is now open.")
print("File %s is now open." % ui)

Another problem beyond the one you asked about: 您询问的问题之外的另一个问题:

r = open(ui, 'r')
print(r)
close.ui()

I assume this is meant to print the contents of the file named by ui . 我认为这是要打印ui命名的文件的内容。 But what it will actually do is to print something like <open file 'filename', mode 'r' at 0x10d7556f0> , and then throw an exception once it hits close.ui() . 但是,实际上将执行的操作是打印<open file 'filename', mode 'r' at 0x10d7556f0> ,然后在遇到close.ui()抛出异常。 r is the file object; r是文件对象; you want to read it, and then close it -- both of these are methods of r : 您想阅读然后关闭它-这两个都是r方法:

r = open(ui, 'r')
print(r.read())
r.close()

Hmm, I see you edited this out of your question while I was typing. 嗯,我看到您在输入时从您的问题中对此进行了编辑。 Hope it helps anyway. 希望它能有所帮助。

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

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