Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

python - Converting many .txt files into csv and combining them

I have many .txt files. I want to convert a few files ending with specific names into csv and combine them into one csv.

### Folder Name: text_files
python_gramm.py
aadd01.txt
aaxx02.txt
aaff03.txt
hhdd01.txt
attd02.txt
auud03.txt
.
.

A text file contains columns of data as given below: enter image description here

I would like to convert only those .txt files having name '___01.txt' to csv format and combine them My code

#### python_gramm.py 
import os
import glob
    os.chdir('text_files/')
    extension = 'txt'
    all_filenames = [i for i in glob.glob('*01.{}'.format(extension))]
    #combine all files in the list
    combined_csv = pd.concat([pd.read_csv(f, delimiter='	') for f in all_filenames ])
    #export to csv
    combined_csv.to_csv( "combined_csv.csv", index=False, encoding='utf-8-sig')

Above code ran successfully without errors.

print(combined_csv)
0      4.18890   9.325750  ...  2.438860e-05            4.100250e+04
1      4.21399   9.339870  ...  2.461170e-05            4.063090e+04
2      4.26399   9.341690  ...  2.451400e-05            4.079280e+04
3      4.80021   9.346420  ...  2.442850e-05            4.093570e+04
4      6.50219   9.339300  ...  2.432250e-05            4.111400e+04
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code says

glob.glob('1.{}'.format(extension))

But I think you mean

glob.glob('*01.{}'.format(extension))

I don't think your glob is finding any files named "1.txt".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...