如何在子文件夹中读取所有文本文件,然后将文件内容(四位数号码)添加到列表中?
我正在学习Python,并且正在尝试读取我拥有的子文件夹中的所有文本文件,并将文件内容(四位数号码)添加到列表中。我只想读取文件扩展名.txt的文件。
我尝试过:
import os
path = "C:\python_projects\PythonProgramming\data-task1\q6" (example)
os.chdir(path)
def read_text_file(file_path):
with open(file_path, 'r') as f:
print(f.read())
for file in os.listdir():
if file.endswith(".txt"):
file_path = f"{path}\{file}"
read_text_file(file_path)
你能帮我吗?太感谢了。
I'm learning python, and I'm trying to read all text files in the subfolders I have, and add the file content (a four-digit number) to a list. I only want to read files with a file extension .txt.
I tried:
import os
path = "C:\python_projects\PythonProgramming\data-task1\q6" (example)
os.chdir(path)
def read_text_file(file_path):
with open(file_path, 'r') as f:
print(f.read())
for file in os.listdir():
if file.endswith(".txt"):
file_path = f"{path}\{file}"
read_text_file(file_path)
Can you please help me? Thank you so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从您当前的代码中,您应该只添加列表和转换。
From your current code, you should just add the list and conversion like so:
我建议使用一个函数,可以递归地使用所有文件夹和子文件夹
I'd recommend using a function, that can be used recursively to go through all folders and subfolders