Common operations of CVS files

1. One-dimensional data storage to CVS file
fo=open('/home/np/下载/price2.cvs','w+')ls=['北京','101.5','120.7','121.4']fo.write(",".join(ls)+"\n")fo.close()




# ",".join(ls) produces a new string formed from the elements in the string ',' separated list ls.

2. Write 2D data to CVS file
For the two-dimensional data stored in the list, the CVS file can be written to the CVS file by cyclically writing one-dimensional data. The reference code style is as follows:
 
 
for row in ls:
    <output file>.write(",".join(row)+'\n')
example:
fo=open('/home/np/download/price2.cvs','w+')
ls=[['Beijing''101.5','120.7','121.4'],['Shanghai''1.1','2','3']]
for row in ls:
    fo.write(",".join(row)+"\n")
fo.close()
The output is:



 3. Import CVS format data to the list:
3.1) Read all data write list at one time
fo=open('/home/np/download/price.cvs')
ls = [];
for line in fo:
    line=line.replace('\n',"")
    ls.append(line.split(","))
print (ls)
fo.close()


Spyder3 output is:
runfile('/home/np/download/test.py', wdir='/home/np/download')
[['Beijing', '101.5', '120.7', '121.4']]


 
 
3.2) Process CVS format data line by line:
Read data from a CVS file, remove commas from the content, and print to the screen.
fo=open('/home/np/download/price2.cvs')
ls = [];
for line in fo:
    line=line.replace('\n',"")
    ls.append(line.split(","))
    lns=""
    for s in ls:
        lns+="{}\t".format(s)
    print(lns)
fo.close()





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325430537&siteId=291194637