我试图创建一个非常简单的程序,用来计算您所写的单词。当我运行我的代码时,我没有得到任何错误,问题是它总是说:"单词的数量是0";当它显然不是0时。我试着添加这个,看看它是否真的从文件print(data)
中读取了任何内容。它不打印任何内容(:所以读取的部分一定有问题。
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
Thx提前
这是因为写入文件后没有关闭文件。在使用z.read()
之前使用f.close()
代码:
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
f.close() # closing the file here after writing
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
输出:
copy ur text down below
hello world
the numbers of words are 2
用f.write
写入f
后,应先用f.close
关闭f
,然后再调用z.read
。请参见此处。