我在 Python For Everyone 第 1.8 节和终端使用方面遇到问题
I am having issues with Python For Everyone Section 1.8 and terminal usage
我正在重新学习 Python 的要点并阅读 Python 适合所有人的书。
我目前停留在涉及终端使用的第 1.8 节。它要求我在终端中使用 Python 程序来扫描文本文件。本书提供了我应该在本节中使用的 python 代码和文本文件。我已经创建了 Python 程序和文本文件,并将它们都放在我的桌面上,因此在同一个文件中。
文件中的Python程序如下所列,名称为words.py.
name = input('Enter file:')
handle = open(name, 'r')
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in list(counts.items()):
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
我创建的文本文件包含以下文本并命名为 clowntext.txt
the clown ran after the car and the car ran into the tent
and the tent fell down on the clown and the car
现在文件 clowntext.txt 和 words.py 又在我桌面上的同一个文件夹中。因此,当我在终端中 运行 Python 程序时,为什么终端提示我没有我指定名称的文件?我在终端中看到的全部内容都在下面的代码中。
Last login: Mon Nov 29 06:33:44 on ttys000
(base) wayneshaw@Waynes-MacBook-Air ~ % python Desktop/words.py
Enter file:clowntext.txt
Traceback (most recent call last):
File "/Users/wayneshaw/Desktop/words.py", line 2, in <module>
handle = open(name, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'clowntext.txt'
您的程序正在当前目录 ~
中查找文件,但 clowntext.txt
在 ~/Desktop
.
中
虽然该程序与您的输入文件位于同一文件夹中,但您是从另一个文件夹启动程序的(您的输入文件位于 ~/Desktop
,但您是从 ~
启动的),并且程序不是从程序所在的文件夹 (~/Desktop
) 中搜索文件,而是从程序启动的文件夹 (~
) 中搜索文件。
您可以为您的程序提供完整路径 Desktop/clowntext.txt
,或将 clowntext.txt
移动到 ~
。
我正在重新学习 Python 的要点并阅读 Python 适合所有人的书。
我目前停留在涉及终端使用的第 1.8 节。它要求我在终端中使用 Python 程序来扫描文本文件。本书提供了我应该在本节中使用的 python 代码和文本文件。我已经创建了 Python 程序和文本文件,并将它们都放在我的桌面上,因此在同一个文件中。
文件中的Python程序如下所列,名称为words.py.
name = input('Enter file:')
handle = open(name, 'r')
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in list(counts.items()):
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
我创建的文本文件包含以下文本并命名为 clowntext.txt
the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car
现在文件 clowntext.txt 和 words.py 又在我桌面上的同一个文件夹中。因此,当我在终端中 运行 Python 程序时,为什么终端提示我没有我指定名称的文件?我在终端中看到的全部内容都在下面的代码中。
Last login: Mon Nov 29 06:33:44 on ttys000
(base) wayneshaw@Waynes-MacBook-Air ~ % python Desktop/words.py
Enter file:clowntext.txt
Traceback (most recent call last):
File "/Users/wayneshaw/Desktop/words.py", line 2, in <module>
handle = open(name, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'clowntext.txt'
您的程序正在当前目录 ~
中查找文件,但 clowntext.txt
在 ~/Desktop
.
虽然该程序与您的输入文件位于同一文件夹中,但您是从另一个文件夹启动程序的(您的输入文件位于 ~/Desktop
,但您是从 ~
启动的),并且程序不是从程序所在的文件夹 (~/Desktop
) 中搜索文件,而是从程序启动的文件夹 (~
) 中搜索文件。
您可以为您的程序提供完整路径 Desktop/clowntext.txt
,或将 clowntext.txt
移动到 ~
。