正确使用readlines()

时间:2016-12-07 23:34:25

标签: python

我正在尝试在我的程序中使用readlines,但是当我使用它时我一直收到错误。我不知道为什么,有人可以帮忙吗?

try:
    filename = input("Please enter the name of the file you would like to examine: ")
    S = open("filename","r")
except:
    print("Cannot open " + filename + "!")

Slines = S.readlines()
li = len(Slines)
words = 0
chars = 0
for item in Slines:
    splitem = item.split()
    words += (len(splitem) - 2)
    chars += (len(item) - 2)


print("In " + filename + "There were:")
print(str(li) + " lines")
print(str(words) + " words")
print(str(chars) + " characters")
S.close()

1 个答案:

答案 0 :(得分:0)

更改行:

S = open("filename","r")

要:

S = open(filename, "r")