Python:无法打开文件进行读取

1 投票
2 回答
1974 浏览
提问于 2025-04-18 03:02

我正在尝试在Windows的命令行中运行一个程序(word_count.py),这个程序是用来处理一个文本文件的。

但是,它在读取文件时出现了错误。有人能告诉我这是为什么吗?

这是我的.py文件:

import sys
import re
import string

def Usage():
print "Usage:word_count.py [doc1] [doc2] ... [docN]"

if len(sys.argv) == 1:
Usage()
sys.exit()

for fn in sys.argv[1:]:
    try:
        with open(fn) as textf:
        word_map = {}
        total_cnt = 0

        # reads one line at a time
        for line in textf:
            line = line.strip()
            if not line:
                continue

            tempwords = line.split()

            for w in tempwords:
                w = re.sub('[%s]' % re.escape(string.punctuation), '', w)
                if w:
                    if w.lower() in word_map:
                        word_map[w.lower()] += 1
                    else:
                        word_map[w.lower()] = 1
                    total_cnt += 1
        print fn+' ------ total word count: '+str(total_cnt)

    output_f_name = 'word_count_'+fn
    with open(output_f_name, 'wb') as output:
        for ele in sorted(word_map.items(), key=lambda x:x[1], reverse=True):
            output.write('{}   {}\n'.format(str(ele[1]).rjust(6), ele[0].ljust(2)))
     except IOError:
        print 'Cannot open file %s for reading' % fn
        exit(1)

我的.py文件和.txt文件都在桌面上,我是通过命令行运行这个程序的,命令是:

c:\Users\Me\Desktop> word_count.py [file.txt]

2 个回答

0

在命令行中,不要在文件名周围加上方括号。

应该这样使用:

word_count.py file.txt

方括号通常用来表示某个参数是可选的,出现在用法说明中。

2

如果你的意思是在命令行中把文件名用方括号括起来,那可能就是问题所在。虽然这些参数被当作一个列表来处理,但实际上是通过空格来分隔列表中的每一项。

撰写回答