【问题标题】:Opening files in directory, storing read values in lowercase list python在目录中打开文件,将读取的值存储在小写列表python中
【发布时间】:2019-12-20 16:02:12
【问题描述】:

我有一个包含 txt 文件的文件夹,我正在尝试附加这些文件,以便将所有内容转换为小写值(我还想做一些进一步的分析,但这是另一天的问题)。

我尝试做的是创建一个空的 lis,然后使用从循环中打开的文件中读取的内容填充该列表,最后使用 list.lower() 将列表中的所有值转换为小写。

我没有收到任何错误消息,但这段代码显然不起作用。

import os
filenames = os.listdir('.')
#Create empty list to store file contents
Lcase_content = []

for filename in filenames:
    if filename.endswith(".txt"):
        with open(os.path.join('.', filename)) as file:
            content = file.read()   
            Lcase_content = content.lower()
            print(Lcase_content)

理想情况下,名为 Lcase_content 的列表包含正在打开的每个文件中内容的所有小写术语。

打印时没有输出,因为列表 Lcase 为空(并且某些原因显示为 str 类型变量而不是列表类型。)

【问题讨论】:

    标签: python-3.x file for-loop


    【解决方案1】:

    您正在将Lcase_content = [] 初始化为一个列表。但是然后你将Lcase_content = content.lower()重新定义/覆盖为字符串

    改为使用Lcase_content.append(content.lower())

    import os
    filenames = os.listdir('.')
    #Create empty list to store file contents
    Lcase_content = []
    
    for filename in filenames:
        if filename.endswith(".txt"):
            with open(os.path.join('.', filename)) as file:
                content = file.read()   
                Lcase_content.append(content.lower())
    print(Lcase_content)
    

    【讨论】:

    • 谢谢。它终于给了我一些东西 - 尽管数组的内容只是空值:['', '', '', ''] - 知道这是为什么吗?
    • 我使用了 print(content),但它没有输出任何东西,所以我假设 with open(os.path...) 行有错误,但不能完全弄清楚什么..
    • 尝试打印出完整路径print(os.path.join('.', filename)) 以检查您是否正在阅读正确的文件。还要检查您的 .txt 文件是否为空。
    • 是的,这很令人困惑。我尝试打印路径,结果很好。我是一个彻头彻尾的白痴。我刚刚检查了文本文件,它们是空的。我一定是在不知不觉中删除了内容。我现在应该删除我的帐户吗?非常感谢你的帮助!哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2018-02-01
    • 2023-01-19
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多