當前位置:首頁 » 編程語言 » python合並csv

python合並csv

發布時間: 2022-06-08 04:07:21

python合並表格報錯

你所定義的list node class和python自帶的list type是不同的東西,不能通用,必須先轉換
其他小錯我直接幫你改掉了
下面是改好可以運行的代碼:
class ListNode(object): def __init__(self,val): self.val = val self.next = None def __repr__(self): return str(self.val) def LinkedList(pythonlist): l = ListNode(pythonlist[0]) c = l for i in range(1,len(pythonlist)): l.next = ListNode(pythonlist[i]) l = l.next return c def PythonList(ListNode): l = [] while ListNode != None: l.append(ListNode.val) ListNode = ListNode.next return l class Solution(object): def mergeTwoLists(self,l1,l2): if l1 is None: return l2 if l2 is None: return l1 mmyhead=ListNode(0) mmyhead.next=None p=mmyhead while l1 is not None and l2 is not None: if l1.val<l2.val: p.next=l1 l1=l1.next else: p.next=l2 l2=l2.next p=p.next if l1 is not None: p.next=l1 else: p.next=l2 return mmyhead.next l1=LinkedList([1,3,5,7])l2=LinkedList([2,4,6,8])sol = Solution()print(PythonList(sol.mergeTwoLists(l1,l2)))

(LinkedList(pythonlist) 方法把一個傳統的python list轉換成你用的首位相銜的listnode 形式,PythonList(ListNode) 則是轉換回來)
同時,linkedlist的數據類型在c裡面比較常用,python裡面一般用不著這么麻煩
希望對你有幫助

㈡ python csv模塊問題請教

csv文件就是文本文件,你可以直接按格式寫入.
但是用python自帶的csv模塊更方便,我也沒怎麼用過,你可以參考以下鏈接.

㈢ python中如何將多個csv文件合並成一個

import glob
import time

csvx_list = glob.glob('*.csv')
print('總共發現%s個CSV文件'% len(csvx_list))
time.sleep(2)
print('正在處理............')
for i in csvx_list:
fr = open(i,'r').read()
with open('csv_to_csv.csv','a') as f:
f.write(fr)
print('寫入成功!')
print('寫入完畢!')
print('10秒鍾自動關閉程序!')
time.sleep(10)

㈣ Python 和 BeautifulSoup 怎麼把 html table 處理成 csv

代碼

#coding:utf8
importurllib
importurllib2
importcookielib
importre
importcsv
importcodecs
frombs4importBeautifulSoup

wiki='https://zh.wikipedia.org/wiki/%E6%96%87%E4%BB%B6%E7%BC%96%E8%BE%91%E5%99%A8%E6%AF%94%E8%BE%83'
header={'User-Agent':'Mozilla/5.0'}
req=urllib2.Request(wiki,headers=header)
page=urllib2.urlopen(req)
soup=BeautifulSoup(page)

name=""#名字
creater=""#歸屬
first=""#首次公開發布的時間
latest=""#最新穩定版本
cost=""#售價
licence=""#授權條款

table=soup.find("table",{"class":"sortablewikitable"})

f=open('table.csv','w')
csv_writer=csv.writer(f)

td_th=re.compile('t[dh]')

forrowintable.findAll("tr"):
cells=row.findAll(td_th)
iflen(cells)==6:
name=cells[0].find(text=True)
ifnotname:
continue
creater=cells[1].find(text=True)
first=cells[2].find(text=True)
latest=cells[3].find(text=True)
cost=cells[4].find(text=True)
licence=cells[5].find(text=True)

csv_writer.writerow([x.encode('utf-8')forxin[name,creater,first,latest,cost,licence]])

f.close()

㈤ PYTHON關於excel和csv轉換

Python處理csv文件時經常會用到講csv文件整體讀取為一個數組或者矩陣的情況,藉助numpy包,可以使用如下代碼簡潔高效低實現: [python] view plain import numpy my_matrix = numpy.loadtxt(open("c:\\1.csv","rb"),delimiter=",",skiprows=0) 將數組或者矩陣存儲為csv文件可以使用如下代碼實現: [python] view plain numpy.savetxt('new.csv', my_matrix, delimiter = ',')

㈥ python如何對數據的列進行規則式合並

首先導入列表中的數組,再對每一列進行檢測若發現相同的數字就用0來填充,在按列求和,生成一個新的數組再合並到原來數組的下面,生成一個新的列表:

import pandas as pd
a=pd.readflie( "XXX.csv") //XXX.csv為你的列表生成的數組文件的路徑
for i in a[i]: //循環找出重復的數據並以0替換
for j in a[i,j]:
if a[i,j]==a[i,j+1]

a[i,j+1]=0

for k in a[k,n]:
for n in a[k,n]:

a[k,n]+=a[k,n]

a[k,n+1]=a[k,n]/n //求平均值

這段代碼復制到pycharn就可以直接運行了,打字不易,求理解

㈦ python實現excel合並

Created on Mon Mar 16 11:23:05 2015
@author: admin
"""
# 分批次運行,先得到books, 再運行,利用print 來debugimport pandas as pd
import numpy as np
import matplotlib as pl
import os
count=0
#ori_path='xx'
ori_path='C:\Python27\data\sample'
def get_xls_books(ori_path): # get target filename and dir of a pathtemp = list(os.walk(ori_path)) #tmp is list ,tmp[0]該目錄文件路徑和文件名, tmp[1]:子目錄文件路徑,文件名稱book_path=[]
book_name=[]
root=temp[0][0]
for i in temp[0][2]:
if os.path.splitext(i)[1] == '.xlsx': #splite filenameobj_path=os.path.join(root,i)
book_path.append(obj_path)
book_name.append(os.path.splitext(i)[0])
return zip(book_path, book_name)
def get_xls_sheets(obj_path): #get all sheets of a object pathxls=pd.ExcelFile(obj_path)
sheet_names=xls.sheet_names
sheets=[xls.parse(i) for i in range(0,len(sheet_names)) ] # use parse can get dataframe saved into a listreturn zip(sheet_names,sheets)
books=get_xls_books(ori_path) # book paths list#xls=pd.ExcelFile(books[0])
#print xls.parse(0).columns
for book in books: # this loop get a bookbookname=book[1]
bookpath=book[0]
sheets=get_xls_sheets(bookpath) # get all sheets and names from book pathfor i in range(len(sheets)): #operate each sheet, is range(len) not lensheetname=sheets[i][0]
name=bookname+'-'+sheetname+'.'+'csv'
pd_sheet=sheets[i][1] # dataFrame
cols=pd_sheet.columns
pdf=pd_sheet[[cols[17],cols[18],cols[4],cols[6],cols[8],cols[10],cols[19],cols[16]]] # use emunerate functionpdf.columns=['area','patch','wangdian','operator','custid','servid','servtype','is_identify'] # renamepdf1=pdf[pdf['is_identify']=='是'] #filterpdf2=pdf1.drop('is_identify',1)
pdf2.to_csv(os.path.join(ori_path,name), header=None, index=None)

㈧ 怎麼用python把一個*。csv 文件裡面的數據整合成一個表格

假設你這里是一個大文件。用CSV預設配置不能讀大文件。我們自己寫一個。

defreadfile(fn):
fp=open(fp,'rb')
whileTrue:
line=fp.readline()
ifnotline:break
line=line.strip()
yieldline.split(',')
fp.close()
importos,sys,time,glob
files=glob.glob("*.csv")
data={}
forfninfiles:
record_number=0
forcolsinreadline(fn):
ifrecord_number==0:
fornameincols:data[name]=[]
else:
forcincols:
data[name].append(c)
record_number+=1
#end

這樣就把所有的文件都讀到一個data變數里了,而且是按列存放的。

㈨ python對多個csv文件里提取指定列匯總到一個新生成的csv文件

#!/usr/bin/envpython
#coding:utf-8

importos
importre


defparserln(ln,patt):
"""用給定的正則表達式解析行"""
matched=patt.match(ln)
ifmatched:
returnmatched.groupdict()


defgetdata(filename,parser,callback=None):
"""用指定的解析方法parser解析指定文件,
用callback進行數據加工過的數據列表
"""
withopen(filename,'rt')ashandle:
returnmap(
callback,
filter(None,map(parser,handle))
)


defstorage(filename,dataserial,spliter=','):
"""將數據序列按行存儲到指定文件,
每一序列元素間用指定的字元分割"""
withopen(filename,'wt')ashandle:
handle.writelines([
"%s "%(spliter.join(map(str,item)))
foritemindataserial
])


if__name__=="__main__":
patt=re.compile(
r"""^
(?P<month>d+),
(?P<amount>d+),
(?P<usage>d+)
s*$""",
re.I|re.U|re.X)
datapath='datasource'
#datasource下所有存在"usage.csv"文件的子目錄
subpaths=[
os.path.join(datapath,path)
forpathinos.listdir(datapath)
if(os.path.isdir(os.path.join(datapath,path))
andos.path.exists(
os.path.join(datapath,path,"usage.txt"))
)
]
storage(
'store.csv',
zip(*map(
lambdapath:getdata(
os.path.join(path,"usage.csv"),
#解析方法為用patt解析行
parser=lambdaln:parserln(ln,patt),
#數據加工方法是取出"amount"轉成整數
callback=lambdax:int(x["amount"]),
),
subpaths))
)

$ tail -n 12 datasource/*/*.csv
==> datasource/2014/usage.csv <==
1,4234,423
2,3523,432
3,4352,438
4,4792,458
5,4823,834
6,5093,734
7,4743,832
8,5152,859
9,4932,810
10,4993,802
11,4999,810
12,5052,850

==> datasource/2015/usage.csv <==
1,5234,423
2,4523,432
3,5352,438
4,5792,458
5,6823,834
6,6093,734
7,6743,832
8,7152,859
9,6932,810
10,6993,802
11,6999,810
12,7052,850
(venv)tim@crunchbang:~/workspace/$

$ cat store.csv
4234,5234
3523,4523
4352,5352
4792,5792
4823,6823
5093,6093
4743,6743
5152,7152
4932,6932
4993,6993
4999,6999
5052,7052
$

㈩ python 如何把多個文件內容合並到以一個文件

Python編程將多個文件合並,代碼如下:

#例子:合並a.txt、b.txt、c.txt合並成d.txt文件

#文件列表,遍於讀取

flist = ['a.txt','b.txt','c.txt']

#要寫入的文件

ofile = open('d.txt', 'w')

#遍歷讀取所有文件,並寫入到輸出文件

for fr in flist:
for txt in open(fr, 'r'):
ofile.write(txt)
ofile.close()
效果如下:

熱點內容
linuxshell入門 發布:2024-05-21 06:44:26 瀏覽:756
如何用手機設置qq郵箱密碼 發布:2024-05-21 06:42:56 瀏覽:60
映像壓縮 發布:2024-05-21 05:46:53 瀏覽:726
小葫蘆直播助手伺服器地址 發布:2024-05-21 05:46:51 瀏覽:969
遨遊緩存視頻 發布:2024-05-21 05:46:47 瀏覽:784
家用電腦能裝伺服器 發布:2024-05-21 05:45:56 瀏覽:437
閉魚腳本 發布:2024-05-21 05:45:54 瀏覽:67
動態范圍壓縮開還是關 發布:2024-05-21 05:44:23 瀏覽:549
本田crv兩驅買哪個配置 發布:2024-05-21 05:41:22 瀏覽:75
手機淘寶緩存視頻 發布:2024-05-21 05:21:09 瀏覽:348