python關於csv檔案
阿新 • • 發佈:2018-11-25
今天我總結了python相關檔案的儲存,下面介紹這個較為常用的方法。
1.csv檔案的儲存與讀取
第一步:匯入csv模組,import csv
第二步:相關資料的梳理,例如:我把相關的資料用列表儲存下來,然後再進行儲存,例如我下面儲存的資訊:
student_list = [] print("請輸入名字") name=input() student_list.append(name) print("請輸入年齡") age = input() student_list.append(age) print("請輸入電話") phone = input() student_list.append(phone)
如上,我建立了一個列表將所需要的資料儲存,如上,student_list儲存了相關的資料,然後,我們需要另外一個列表儲存這個列表all=[]
,使用這個將每次儲存的資料再次儲存下來即可,如下,我使用了
def save():
def add_list():
def select():
三個方法,最後使用儲存的方法:
def save(): with open("E:\\study.csv","w+",newline="",encoding="utf-8_sig")as f: writer = csv.writer(f) writer.writerow(["名字", "年齡", '電話']) for row in all: writer.writerow(row)
即可將其儲存,並且每次迴圈使用:
程式碼如下:
if Ture:
x=int(input("請選擇"))
while x not in range(1,2):
print("請重新選擇")
if x==1:
while x ==1:
add_list()
select()
x = int(input("請選擇"))
if x==2:
save()
print("儲存成功,謝謝您的使用")
下面具體程式碼測試效果如下:
測試:
如上,我們是列表裡面添加了列表,然後即可儲存。我們開啟相關的檔案檢視:
我麼所需要的資料即儲存下來了。
下面,我們即可以看到這個程式裡面最重要的部分,即為
def save()
with open("E:\\study.csv","w+",newline="",encoding="utf-8_sig")as f:
中,即為開啟為study.csv的文件,“w+”讀寫,newline=""即為除去換行,encoding=“utf-8_sig"為修改編碼為"utf-8_sig”,
writer.writerow([“名字”, “年齡”, ‘電話’])即為寫入一行,為名字,年齡,電話的一行資料,
for row in all:
writer.writerow(row)
最後使用這個將其遍歷all,將所有的資料儲存進去即可
第三步
下面即可學習讀取檔案:
def read():
x=os.path.exists("E:\\study.csv")
if x==True:
f = csv.reader(open("E:\\study.csv", "r", encoding="utf-8_sig"))
for row in f:
print(row)
先檢視是否存在此檔案,如果存在即使用如下:
f = csv.reader(open(“E:\study.csv”, “r”, encoding=“utf-8_sig”))
即可檢視此檔案內容
for row in f:
print(row)
然後遍歷輸出即可!
以上即為csv的相關使用方法