Python 3.x 在目录中打开文件,以小写列表形式存储读取值
我有一个包含txt文件的文件夹,我正试图附加这些文件,以便将所有内容转换为小写值(我还想做一些进一步的分析,但这是另一天的问题) 我试图做的是创建一个空lis,然后用循环中打开的文件中的读取内容填充该列表,最后使用list.lower()将列表中的所有值转换为小写 我没有收到任何错误消息,但这段代码显然不起作用Python 3.x 在目录中打开文件,以小写列表形式存储读取值,python-3.x,file,for-loop,Python 3.x,File,For Loop,我有一个包含txt文件的文件夹,我正试图附加这些文件,以便将所有内容转换为小写值(我还想做一些进一步的分析,但这是另一天的问题) 我试图做的是创建一个空lis,然后用循环中打开的文件中的读取内容填充该列表,最后使用list.lower()将列表中的所有值转换为小写 我没有收到任何错误消息,但这段代码显然不起作用 import os filenames = os.listdir('.') #Create empty list to store file contents Lcase_content
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类型变量而不是列表类型)。您正在将
Lcase\u content=[]
初始化为列表。但随后您将其重新定义/覆盖为字符串
使用Lcase\u content.append(content.lower())
谢谢你。它终于给了我一些东西-虽然数组的内容只是空值:['','','','','',]-知道为什么吗?我使用了print(content),但它没有输出任何东西,所以我假设with open(os.path…)行有一个错误,但不太清楚是什么..试着打印出整个文件路径
print(os.path.join)(“.”,文件名))
检查您是否读取了正确的文件。同时检查您的.txt
文件是否不正确。是的,这很混乱。我尝试打印路径,结果很好。我是个十足的白痴。我只是检查了文本文件,但它们是空的。我一定是在不知不觉中删除了内容。我现在应该删除我的帐户吗?非常感谢你的帮助!哈哈
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)