1. 程式人生 > >python文件讀寫-----csv的使用

python文件讀寫-----csv的使用

imp index索引 lose 列表 年齡 size 一個 遍歷 數據

首先來看看原始的讀取:

f= open(file,r)
stat = f.readlines()
print(stat)

輸出的結構是一個整體的列表。

[‘姓名,性別,年齡,愛好,人脈,學習\n‘, ‘0,8,0,9,0\n‘, ‘1,9,1,10,1\n‘, ‘2,10,4,11,2\n‘, ‘3,11,9,12,3\n‘, ‘4,12,16,13,4\n‘, ‘5,13,25,14,5\n‘, ‘6,14,36,15,6\n‘, ‘7,15,49,16,7\n‘, ‘8,16,64,17,8\n‘, ‘9,17,81,18,9\n‘, ‘10,18,100,19,10\n‘, ‘11,19,121,20,11\n‘‘]

采用csv模塊操作,能更方便的進行數據的操作:

with open(file,r) as file:
    reader = csv.reader(file)
    lines = [line for line in reader]
    print(lines)

[[‘姓名‘, ‘性別‘, ‘年齡‘, ‘愛好‘, ‘人脈‘, ‘學習‘], [‘0‘, ‘8‘, ‘0‘, ‘9‘, ‘0‘], [‘1‘, ‘9‘, ‘1‘, ‘10‘, ‘1‘], [‘2‘, ‘10‘, ‘4‘, ‘11‘, ‘2‘], [‘3‘, ‘11‘, ‘9‘, ‘12‘, ‘3‘], [‘4‘, ‘12‘, ‘16‘, ‘13‘, ‘4‘], [‘5‘, ‘13‘, ‘25‘, ‘14‘, ‘5‘], [‘6‘, ‘14‘, ‘36‘, ‘15‘, ‘6‘]]

一、csv的寫操作:

import csv
csvflie= open(file,w,newline=‘‘)  #newline指的是文件的最後none--->\n
try:
    writer = csv.writer(csvfile)#構建一個寫的對象
    print(type(writer))
    writer.writerow=((姓名,行唄,學號))#往裏面寫數據
    for i in range(10):
        writer.writerow=((i,i+1,i*i))#註意切記!無等號
    print(chengg)

except
Exception as c: print(c) print(操作失敗) finally: csvfile.close()

1.1查看文件的大小

def get_size(path):
    file_size = os.path.getsize(path)
    print(file_size)

get_size(file)

二、csv文件的讀取操作

方法一:用index索引重新寫入

import csv
with open(file,r) as file:
    reader = csv.reader(file)
    rows =[row for row in reader] #把reader遍歷在一個列表中
    for line in rows:
        print(line)
        for index,i in enumerate(line):#把每個元素取出來
            with open(rC:\Users\jeep-peng zhang\Desktop\demo.txt,a) as file_new:
                if index==len(line)-1:#換行
                    file_new.write(i+\n)
                else:
                    file_new.write(i+ )
                file_new.close()

方法二:

import csv
with open(file,r) as file:
    reader = csv.reader(file)
    lines = [line for line in reader]#循環把他存在列表裏面
    for result in lines:#把列表裏面的東西循環出來
        line_str = ,.join(result)#用逗號隔開
        print(line_str)
        with open(rC:\Users\jeep-peng zhang\Desktop\demo.txt,a) as new_file:
            # writer = csv.writer(new_file)
            # writer.row(line_str+‘\n‘)
            new_file.write(line_str+\n)

python文件讀寫-----csv的使用