正如标题所说,我在通过pythonshell运行命令时遇到了一些问题,更具体地说,我似乎不知道如何打开和读取文件,就像它在学习练习中告诉我的那样。在
以下是我目前所做的一切:
PS C:\Users\NikoSuave\Desktop\learn python the hard way\works in progress or finished> python
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import argv
>>> script, filename = argv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
>>> txt = open(filename)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'filename' is not defined
>>> filename = argv
>>> script = argv
>>> txt = open(filename)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, list found
我做错什么了?如果我走远了,你们能给我指个正确的方向吗?在
或者首先定义所有字符串的字符串。在
或者
^{pr2}$在这个问题中:
在系统argv返回列表,python抱怨需要字符串或缓冲区,而不是列表。所以你必须找到列表中的每一个元素并把它们放到正确的位置。在
sys.argv
是Python中的一个列表,其中包含传递给脚本的命令行参数。所以这通常在运行python程序时使用。使用命令行,如:这里}出现在
arg1
和{argv
列表中。在REPL中时没有参数传递给,因此argv
为空。这就是你一直得到ValueError
,NameError
。。。在至于打开一个文件,就像:
^{pr2}$file_object = open(filename, mode)
,其中mode
可以是r, w, a, r+
(读、写、追加和读写)。例如:上面的代码打开
newfile.txt
进行写入,并添加显示的内容。最后关闭文件。在读取文件时也可以使用类似的内容:这将读取文件
newfile.txt
并打印内容。在看起来你应该创建一个.py文件。然后使用另一个文本文件的名称参数运行该文件。系统argv从命令行获取参数。在
相关问题 更多 >
编程相关推荐