Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...