python读写csv文件
❶ python 读取多个csv文件中某一列,并生成一个新csv文件
csv文件来应该是用逗号分隔得才对源,否则怎么算作是csv文件。楼主你开玩笑吧。否则你这只是一个普通的文本文件。如果是真正的csv文件,我只说一点,python里面有csv模块,专门处理csv文件。如果是空格分割应该也可以,建议你,看一下python的csv模块的API,蛮简单的代码,其实如果不用的话自己写也可以。不是很复杂。代码片段如下:
defdeal_file(file_in,file_out)
withopen(file_in,'r')asf_in:
withopen(file_out,'w')asf_out:
forlineinf_in:
f_out.write(line.split('')[2]+' ')
之后你可以将所有的输入文件放到一个列表里面,进行迭代调用这个函数就可以了。
❷ python3中使用使用read_csv( )读取csv文件,文件路径中含有中文,怎么处理
最顶上这样写:
#!/usr/bin/env python
# coding: utf-8还有文件名的引号前加u
❸ python中怎样读取csv文件内容
和普通文件一样读取。csv中文件数据项有回逗号划分开。答
12345infile = open("data.csv", 'r') for line in infile: data = line.rstrip().split(',') print(data)
❹ 请教PYTHON读取CSV文件方法
#!/usr/bin/python
#-*-coding:UTF-8-*-
fromLogimportLoginfo
importcgi,os,csv,sys,re
reload(sys)
sys.setdefaultencoding('utf8')
print"Content-Type:text/htmlcharset=utf-8 "
fileitem=''
defget_cgi_file():
''''''
globalfileitem,device_id,maxDeviceID,maxDriverID,channelid,ChannelDeviceType
form=cgi.FieldStorage()
#获取文件名
fileitem=form['filename1']
#检测文件是否上传
iffileitem.filename:
#去掉文件路径,获取文件名称
fn=os.path.basename(fileitem.filename)
open(global_var.uploadfile_path,'wb').write(fileitem.file.read())
#message='文件"'+fn+'"上传成功!'
#printmessage
else:
message='没有文件上传!'
printmessage
defconvert_gbk2utf8():
data_list=[]
fd=open(global_var.uploadfile_path,'rb')
csvfd=csv.reader(fd)
forc1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14incsvfd:
c1_u=c1.decode('gb2312').encode('utf-8')
c2_u=c2.decode('gb2312').encode('utf-8')
c3_u=c3.decode('gb2312').encode('utf-8')
c4_u=c4.decode('gb2312').encode('utf-8')
c4_u=c4.decode('gb2312').encode('utf-8')
c5_u=c5.decode('gb2312').encode('utf-8')
c6_u=c6.decode('gb2312').encode('utf-8')
c7_u=c7.decode('gb2312').encode('utf-8')
c8_u=c8.decode('gb2312').encode('utf-8')
c9_u=c9.decode('gb2312').encode('utf-8')
c10_u=c10.decode('gb2312').encode('utf-8')
c11_u=c11.decode('gb2312').encode('utf-8')
c12_u=c12.decode('gb2312').encode('utf-8')
c13_u=c13.decode('gb2312').encode('utf-8')
c14_u=c14.decode('gb2312').encode('utf-8')
data_row_list=[c1_u,c2_u,c3_u,c4_u,c5_u,c6_u,c7_u,c8_u,c9_u,c10_u,c11_u,c12_u,c13_u,c14_u]
data_list.append(data_row_list)
fd.close()
#log.write_debug(data_list)
returndata_list
defanaly_csv_file(data_list):
forrownuminrange(len(data_list)):
ifrownum==0:
attrib=data_list[rownum]
else:
foriinrange(len(attrib)):
#这里循环取数据,依据是列名
ifattrib[i]=='你的列名':
printdata_list[rownum][i]
if__name__=='__main__':
log=Loginfo.Loginfo()
get_cgi_file()
try:
data_list=convert_gbk2utf8()
exceptExceptionase:
print("正在导入的表格列数不对,请检查!")
deleteDevice()
删了一些函数,这样应该可以看得懂吧,c14_u是列,有多少列就多少个,这是转换编码。analy_csv_file(data_list)里面对拿到的文件做处理
❺ Python 如何读取.csv文件的单个列
import xlrd
EXCEL_BOOK_FULLNAME='FULL FILE NAME'
workbook=xlrd.open_workbook(EXCEL_BOOK_FULLNAME)
worksheet=workbook.sheet_by_name('Sheet1')
rows=worksheet.nrows #worksheet rows
cols=worksheet.ncols #worksheet columns
lists=[[],[],[],[]] #modify this according your column counts
for c in range(cols): #transfer excel values into lists
for r in range(rows):
lists[c].append(worksheet.cell_value(r,c))
❻ 如何用python读入csv文件
class DBI(object):
"""database interface"""
def __init__(self, conn):
"""keep connection"""
self._conn = conn
def store(self, sql, data):
"""store data into database with given sql"""
curr = self._conn.cursor()
curr.executemany(sql, data)
self._conn.commit()
curr.close()
def execute(self, sql, *args, **kwgs):
"""execute sql on database"""
curr = self._conn.cursor()
curr.execute(sql, *args, **kwgs)
self._conn.commit()
curr.close()
❼ 利用Python如何将数据写到CSV文件中
如果你的数据是列表格式,可以使用一个迭代器,将数据写入文件,同时添加必回要的分隔符以构成csv文件
如果数据答是字典格式,需要考虑使用换行符或者其他特殊符号来分割每个字典元素(包括键和值)。键和值可以考虑使用和之前不重复的分隔符进行分割。
这样就构成了一个csv文件(csv使用分隔符分割值的文件)
操作方法如下:
1,使用读写追加的方式打开csv文件。
2,找到csv文件的结尾。
3,在结尾使用和之前csv使用的分割相同的格式进行数据添加。
4,关闭文件
❽ Python怎么把输出整体写入CSV文件
在试了n多方案 ironpython, eric, winpdb, pyscripter, ipython之后, 选择了一个超级简单的方案: code, telnetlib, 然后问题就解决了.
❾ python怎么写入csv文件
import pandas as pd#任意的多组列表a = [1,2,3]
b = [4,5,6]
#字典中的key值即为csv中列名dataframe = pd.DataFrame({'a_name':a,'b_name':b})#将DataFrame存储为csv,index表示是否显示行名,default=Truedataframe.to_csv("test.csv",index=False,sep='')1234567891011
a_name b_name0 1 41 2 52 3 61234
同样pandas也提供简单的读csv方法
import pandas as pddata = pd.read_csv('test.csv')12
会得到一个DataFrame类型的data,不熟悉处理方法可以参考pandas十分钟入门
另一种方法用csv包,一行一行写入
import csv
#python2可以用file替代open
with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile)
#先写入columns_name
writer.writerow(["index","a_name","b_name"])
#写入多行用writerows
writer.writerows([[0,1,3],[1,2,3],[2,3,4]])12345678910
index a_name b_name0 1 31 2 32 3 41234
读取csv文件用reader
import csvwith open("test.csv","r") as csvfile:
reader = csv.reader(csvfile) #这里不需要readlines
for line in reader:
print line