尝试的第一种,只能获取一级的目录
import os
path = "D:\\Anaconda\\code\\dataset\\enron_mail_20150507"
datanames = os.listdir(path)
for i in datanames:
print(i)
>>>maildir
换了个路径试了试
path = "C:/Users/lenovo/Desktop/2000_conference"
datanames = os.listdir(path)#只能读取path下面的最直接的一个文件夹
for i in datanames:
print(i)
>>>
1_.txt 2_ 3_ 8hdhwe inbox
输出的是第一级文件的名字和子文件夹的名字,没有第二级的信息
Python os.walk() 方法
import os
for root, dirs, files in os.walk(".", topdown=False):
#root 当前文件夹本身的地址
#dirs 一个list 文件夹中所有目录的名字
# files 文件夹中的所有文件的名字
#topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
for name in files:
print(os.path.join(root, name))#会输出所有层级的文件名字
for name in dirs:
print(os.path.join(root, name))#输出所有的文件夹路径
>>>
C:/Users/lenovo/Desktop/2000_conference\8hdhwe\test\1233333.txt C:/Users/lenovo/Desktop/2000_conference\8hdhwe\test C:/Users/lenovo/Desktop/2000_conference\inbox\1_ C:/Users/lenovo/Desktop/2000_conference\inbox\2_ C:/Users/lenovo/Desktop/2000_conference\inbox\3_ C:/Users/lenovo/Desktop/2000_conference\inbox\4_ C:/Users/lenovo/Desktop/2000_conference\inbox\5_ C:/Users/lenovo/Desktop/2000_conference\1_.txt C:/Users/lenovo/Desktop/2000_conference\2_ C:/Users/lenovo/Desktop/2000_conference\3_ C:/Users/lenovo/Desktop/2000_conference\8hdhwe C:/Users/lenovo/Desktop/2000_conference\inbox
python 输出打印到文件中
import os
import sys
temp = sys.stdout
f = open('test.txt','w')#没有文件也会创建一个这个文件
print('asdf') # 打印到终端
# 之后使用print函数,都将内容打印到test.txt 文件中
sys.stdout = f
print('a') # 打印到文件中
# 恢复print函数打印到终端上
sys.stdout = temp
print('sdffg') # 打印到终端
f.close()
python怎么批量读取文件_python如何批量读取txt文件
python怎么批量读取文件_python如何批量读取txt文件_宋不负的博客-CSDN博客
import os
path = "G:\数据分析篇\携程游记之避暑2019年共1267篇" #文件夹目录
files= os.listdir(path) #得到文件夹下的所有文件名称
txts = []
for file in files: #遍历文件夹
position = path+'\\'+ file
print (position)
with open(position, "r",encoding='utf-8')as f: #打开文件
lines = f.readlines() #读取文件中的一行
for line in lines:
txts.append(line)
f.close()
print (txts)
用原文的方式会报错。文件内容不是字符串 ,只能按行append。
对原文中的代码,做了一些修改。
----最终把所有的文件内容都读出来----(变成了列表形式,还不太满意)
import os
txts = []
for root, dirs, files in os.walk("C:\\Users\\lenovo\\Desktop\\2000_conference", topdown=False):
for name in files:
a = os.path.join(root,name)
print(a)#可不打印
with open(a, "r") as f: #打开文件
lines = f.readlines() #读取文件中的一行
for line in lines:
txts.append(line)
print (txts)
读一个文件,内容格式不变(我的是一个邮件)
f = open('C:\\Users\\lenovo\\Desktop\\2000_conference\\2_ ', 'r')
x =f.read()
# Lowercase the text
x = x.lower()
print(x)
##小写
x1 = x.encode('ascii', 'ignore').decode()
print(x1)
##去掉ascii
效果大致如下:
后续继续修改