【问题标题】:Formatted output for dictionary that shows information about files显示文件信息的字典的格式化输出
【发布时间】:2022-01-25 08:55:58
【问题描述】:

我是 Python 新手,我正在尝试编写一个程序,该程序将读取文本文件列表并返回一个字典,其中包含 filePaths 以及每个文件中有多少 m

通过搜索互联网,我想出了以下代码:

def readFilesFor_m(filePaths):
    # dictionary for saving no of m's in each file
    dictionary = {}
    
    for filePath in filePaths:
        fileObj = open(filePath, "r");
        fileContent = fileObj.read()
        dictionary[fileObj] = fileContent.count('m');
    fileObj.close()
    return dictionary


fileLists = [
    "H:\\SomeTextFiles\\16.txt",
    "H:\\SomeTextFiles\\Chat.txt",
    "H:\\SomeTextFiles\\zero-m.txt"
]
print(readFilesFor_m(fileLists))

程序运行,但我看到的输出并不像我想象的那么简单(想要的):

{<_io.TextIOWrapper name='H:\\SomeTextFiles\\16.txt' mode='r' encoding='cp1252'>: 581, 
     <_io.TextIOWrapper name='H:\\SomeTextFiles\\Chat.txt' mode='r' encoding='cp1252'>: 20, 
     <_io.TextIOWrapper name='H:\\SomeTextFiles\\zero-m.txt' mode='r' encoding='cp1252'>: 0}

我不想字典里有那些多余的东西,我只想看看,

{'H:\\SomeTextFiles\\16.txt': 581, 'H:\\SomeTextFiles\\Chat.txt': 20, 'H:\\SomeTextFiles\\zero-m.txt': 0}

我需要做什么才能实现这一目标?

【问题讨论】:

  • 只需将dictionary[fileObj] 替换为dictionary[filePath]
  • 我已经找到了,+1

标签: python-3.x file dictionary


【解决方案1】:

您看到的文本是 fileObj 的字符串表示形式,您已将其用作字典中的键。只需改用filePath,因为您已经将路径作为字符串。

dictionary[filePath] = fileContent.count('m')

此外,您在每次迭代中打开一个新的文件对象,但只在循环外关闭它一次。最好在循环内部关闭,或者使用 with 块为您处理它。

【讨论】:

  • 关于文件关闭的好消息。
  • 更新了循环内的文件关闭,我怎样才能将代码改进到更好的标准,比如使用 try-catch 块。 @shriakhilc
  • @abhimanyue,您可以从 PEP8 的建议开始。例如,snake_case 而不是 camelCase 用于变量名称。
猜你喜欢
  • 1970-01-01
  • 2018-05-24
  • 2010-10-30
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多