pythoncsv亂碼
❶ python讀取csv文件時,數據內容含有中文,讀取出錯,怎麼辦
估計是亂碼造成,需要在讀取的py文件中指定編碼格式:
在文件開頭,設置成gbk格式import
os,sys,re,csv
reload(sys)
sys.setdefaultencoding('gbk')
❷ python讀取csv文件的某一行
1.全部讀到成列表然後選取行(容易超時,亂碼等問題)
2.利用迭代工具,代碼如下:
from itertools import islice
with open('data.tsv', 'r') as f:
for line in islice(f, 1, None):
# process data
f.close()
修改islice函數中第2個參數n即可,表示讀到f文件對象的第n行
❸ python讀取csv文件中文字元亂碼
用chardet查下編碼
然後解碼 用『utf-8』編碼
❹ python怎麼實現CSV批處理,並把文件名和文件夾名添加到後兩列
#encoding: utf-8__author__ = 'DELL'import csvimport globimport datetimeimport sysimport osreload(sys)#中文錯誤sys.setdefaultencoding( "utf-8" )'''@author likehua CSV批處理'''class BatchProcessCSV: def __init__(self,inputfolder="c:\\input\\",outputfolder="c:\\output\\"): self.inputfolder=inputfolder self.outputfolder=outputfolder #批處理 def doBatchAction(self): startTime=datetime.datetime.now() print(u"開始處理...") if (os.path.exists(self.outputfolder)==False): #pass os.makedirs(self.outputfolder) list_dirs = os.walk(self.inputfolder) for root, dirs, files in list_dirs: #print i for file in files: otput=self.outputfolder+file self.readcsv2csv(self.inputfolder+file,otput) print(u"Running.........................\n") endTime=datetime.datetime.now() print(u"處理完成,耗時:%f秒"%(endTime-startTime).seconds) #讀取一個csv提取部分信息生成新的CSV def readcsv2csv(self,inputfile,outputfile): with open(inputfile, 'rb') as csvfile: o=open(outputfile,"wb") #解決csv瀏覽亂碼問題 o.write('\xEF\xBB\xBF'); writer=csv.writer(o) #讀取列 將字元串轉為數組 column=csvfile.readline().split(",") #print(column.index('App Release Date')) #print(column) writer.writerow(['Rank' ,'Category', 'Country ','App Name', 'Value', 'Unit' , 'App Release Date', 'Publisher Name', 'Company Name', 'Parent Company Name']) reader = csv.reader(csvfile) #table = reader[0] #Rank, Category, Store, Device, Type, Country, Period,Version, App_ID, App_Name, Value, Unit, Value_Type, AppURL, App_IAP, App_Category, App_Device, Current_Price, App_Release_Date, Publisher_ID, Publisher_Name, CompanyName, ParentCompanyName, AppNameUnified, AppFranchise, UnifiedAppID, AppFranchiseID, CompanyID, ParentCompanyID for row in reader: lenth=len(row) if lenth>10: writer.writerow([row[column.index("Rank")],row[column.index("Category")],row[column.index("Country")],row[column.index("App Name")],row[column.index("Value")],row[column.index("Unit")],row[column.index("App Release Date")],row[column.index("Publisher Name")],row[column.index("Company Name")],row[column.index("Parent Company Name")]]) #processif __name__=="__main__": csvProcess=BatchProcessCSV("c:\\input\\","e:\\output\\") csvProcess.doBatchAction()
❺ 求助大佬python3 寫入CSV亂碼的問題
在windows下打開需要使用gbk encode python中的中文字元。