我們有時候會批量處理同一個文件夾下的文件,并且希望讀取到一個文件里面便于我們計算操作。比方我有下圖一系列的txt文件,我該如何把它們寫入一個txt文件中并且讀取為dataframe格式呢?
首先我們要用到glob模塊,這個python內置的模塊可以說是非常的好用。
1
|
glob.glob( '*.txt' ) |
得到如下結果:
all.txt是我最后得到的結果文件。可以見返回的是一個包含txt文件名稱的列表,當然如果你的文件夾下面只有txt文件,那么你用os.listdir()可以得到一個一樣的列表
然后讀取的時候只要注意txt文件的編碼格式(可以用notepad++打開記事本查看)和間隔符的形式就好了,完整的代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import os import pandas import codecs import glob import pandas as pd os.getcwd() os.chdir( 'd:\aaaasxq\python study\data preprocessing' ) def txtcombine(): files = glob.glob( '*.txt' ) all = codecs. open ( 'all.txt' , 'a' ) for filename in flist: print (filename) fopen = codecs. open (filename, 'r' ,encoding = 'utf-8' ) lines = [] lines = fopen.readlines() fopen.close() i = 0 for line in lines: for x in line: all .write(x) #讀取為dataframe格式 all1 = pd.read_csv( 'all.txt' ,sep = ' ' ,encoding = 'gb2312' ) #保存為csv格式 all1.to_csv( 'all.csv' ,encoding = 'gb2312' ) if __name__ = = '__main__' : txtcombine() |
以上這篇python批量讀取txt文件為dataframe的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/m0_37324740/article/details/78040749