这是我的代码
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
如果文件名中有空格,我正在Windows上运行它 例如“某些文件xyz.txt”
然后在运行以上代码时出现错误
Enter file name: "some file xyz.txt"
Enter word to be searched:cs
Traceback (most recent call last):
File "D:/folder1/folder2/folder3/some file xyz.txt", line 5, in <module>
with open(fname, 'r') as f:
OSError: [Errno 22] Invalid argument: '"some file xyz.txt"'
>>>
我应该如何用空格输入正确的文件名,或者代码本身是错误的?
答案 0 :(得分:0)
只需输入不带引号的文件名。 Python将您的输入视为整个字符串。