艰难地学习Python示例15 pythonshell问题

2024-04-19 21:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题所说,我在通过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

我做错什么了?如果我走远了,你们能给我指个正确的方向吗?在


Tags: orinmostmorestdinlinescriptcall
3条回答

或者首先定义所有字符串的字符串。在

>>> txt = open(filename)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'filename' is not defined

This is not how we open files with python, you need strings.
txt=open("filename.txt") #if is it a txt file

或者

^{pr2}$

在这个问题中:

>>> 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

在系统argv返回列表,python抱怨需要字符串或缓冲区,而不是列表。所以你必须找到列表中的每一个元素并把它们放到正确的位置。在

sys.argv是Python中的一个列表,其中包含传递给脚本的命令行参数。所以这通常在运行python程序时使用。使用命令行,如:

python prog.py arg1 arg2

这里arg1和{}出现在argv列表中。在REPL中时没有参数传递给,因此argv为空。这就是你一直得到ValueErrorNameError。。。在

至于打开一个文件,就像:file_object = open(filename, mode),其中mode可以是r, w, a, r+(读、写、追加和读写)。例如:

^{pr2}$

上面的代码打开newfile.txt进行写入,并添加显示的内容。最后关闭文件。在读取文件时也可以使用类似的内容:

file = open("newfile.txt", "r")
print file.read()

这将读取文件newfile.txt并打印内容。在

看起来你应该创建一个.py文件。然后使用另一个文本文件的名称参数运行该文件。系统argv从命令行获取参数。在

相关问题 更多 >