【发布时间】:2021-09-28 05:51:58
【问题描述】:
不明白(在 Coursers 上传递任务)第二个代码如何读取文件内容。没有 ".readline"、".readlines" 方法。 第一个跑不了。 任务(文件包含单词行数,需要统计单词数)
#the first
file = open('/Users/max/Desktop/education/Test_record.csv', 'r')
num_words = 0
for lines in file.readlines():
line = file.split()
num_words += len(line)
print(num_words)
#file.close()
#the second (runs well)
num_words = 0
fileref = "/Users/max/Desktop/education/Test_record.csv"
with open(fileref, 'r') as file:
for line in file:
num_words += len(line.split())
print(num_words)
#file.close()
【问题讨论】:
-
欢迎来到 Stack Overflow。在这里查看这篇关于提出好问题的文章:stackoverflow.com/help/how-to-ask 如果不分享任何实际代码,我们几乎不可能为您提供帮助
-
for循环为什么要缩进?
-
你应该做的是
lines.split()在第一个。 -
为什么?我在循环迭代行时这样做