简体   繁体   中英

convert .txt file to .csv file using python

enter image description here AR = 0.9995 N2 = 0.000 HE = 0.000
KR = 0.000 H2 = 6.3998E-08 H = 4.2639E-15 H2O = 0.000 CO2 = 0.000 CO = 0.000
CH4 = 6.6510E-08 CH3 = 8.0334E-10 CH2 = 6.7005E-12

my text file is in this form where i would like to transform it into a csv file where the names od the species is in a row and the corresponding numbers in a row I would really appreciate any help.

enter image description here

https://drive.google.com/folderview?id=15MK_sRDOuYD9dTX_2FMmCK7Mdvc9CMfn : this is my text file that I want to transform

Follow the steps,

  1. Split the texts appropriately
  2. Make a new csv file
  3. Use Python's csv module to add the data into it

Let me know if you are not familiar with this kind of stuff. Then I would be more thorough.

I transformed the file into a row, as mentioned in question

 import re import pandas as pd #read the file from a txt #list of files list_files = ['data1.txt','data2.txt'] for j in list_files: f = open(j, "r") data = f.readlines() # joining the text and removing newline and space string = " ".join(data) string = " ".join(re.sub(r'[\\n]', '', string).split()) string = string.replace(' = ', '|').replace('= ', '|') data = {} list_string = string.split(" ") for i in list_string: k = i.split("|") print(k) data[k[0]] = float(k[1]) f.close() df = pd.DataFrame([data]) df.to_csv(f"{j.split('.txt')[0]}.csv", index=False)

在此处输入图片说明

https://docs.google.com/spreadsheets/d/1gqE0KX0Qw1o7SBegv1riIHSczXhhZA4Ot2oYOaEKZN4/edit?usp=sharing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM