简体   繁体   中英

Python script to read a text file and write into a csv file

I have a text file in which each row has multiple words (which I want to consider as columns). Now I want to read all the data from this text file and create a csv file with rows and columns. I am written the code till here -

import csv
f=open("text.txt", "r")
reader=csv.reader(f)
offile=open("output.csv","wb")
writer=csv.writer(offile,delimiter='\t',quotechar='"',quoting=csv.QUOTE_ALL)
for row in reader:
 ........

f.close()
offile.close()

I am not able to understand how to divide each row into columns and write this columns and rows back while writing a csv file? I am a newbie to python, so a good example I will be very greatful.

Thanks

Try splitting the lines via a regular expression:

line = "Foo bar baz quux"
import re
pieces = re.split("\s+", line)
print pieces

This results in

['Foo', 'bar', 'baz', 'quux']

The regular expression used above matches for multiple (+) white space characters (\\s)

import re
data = open("test.txt").read()
lines_of_data = data.splitlines()
writer=csv.writer(offile,delimiter='\t',quotechar='"',quoting=csv.QUOTE_ALL)
writer.writerows(map(lambda line:re.split("\s\s\s\s+",line.strip()),lines_of_data))
data = open('test.txt').read()
lines_of_data = data.splitlines()
tmp = []
for i in range(len(lines_of_data)):
    tmp.append(lines_of_data[i].split())    
data_df = pd.DataFrame(tmp) 
data_df.to_csv('test.csv')

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