利用python 讀寫csv文件
1、讀文件
import csv
csv_reader = csv.reader(open("data.file", encoding="utf-8"))
for row in csv_reader:
print(row)
csv_reader把每一行數(shù)據(jù)轉(zhuǎn)化成了一個(gè)list,list中每個(gè)元素是一個(gè)字符串。
2、寫文件
讀文件時(shí),我們把csv文件讀入列表中,寫文件時(shí)會(huì)把列表中的元素寫入到csv文件中。
list = ["1", "2", "3", "4"] out = open(outfile, "w") csv_writer = csv.writer(out) csv_writer.writerow(list)
可能遇到的問題:直接使用這種寫法會(huì)導(dǎo)致文件每一行后面會(huì)多一個(gè)空行。
解決辦法如下:
out = open(outfile, "w", newline="") csv_writer = csv.writer(out, dialect="excel") csv_writer.writerow(list)
在stackoverflow上找到了比較經(jīng)典的解釋,原來 python3里面對(duì) str和bytes類型做了嚴(yán)格的區(qū)分,不像python2里面某些函數(shù)里可以混用。所以用python3來寫wirterow時(shí),打開文件不要用wb模式,只需要使用w模式,然后帶上newline=''。
3、示例
- 簡單讀寫
import csv
class writer:
def __init__(self):
self.dict = {
"標(biāo)題": "標(biāo)題",
"鏈接": "鏈接",
"服務(wù)": "服務(wù)",
"dsr": "dsr",
"店鋪名": "店鋪名",
"價(jià)格": "店鋪名",
"付款人數(shù)": "付款人數(shù)",
"發(fā)貨地": "發(fā)貨地",
}
out = open("outfile.csv", "w", newline="")
self.csv_writer = csv.writer(out, dialect="excel")
self.csv_writer.writerow(self.dict)
def writer_to(self, key_value):
self.csv_writer.writerow(key_value)
if __name__ == "__main__":
a = writer()
new = {
"鏈接": "http://www.baidu.com",
"標(biāo)題": "我是標(biāo)題",
}
a.dict.update(new)
print(a.dict)
a.writer_to(a.dict.values())
- 結(jié)合爬蟲
import csv
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
driver = ["1", "2"]
colspan = ["1", "2"]
try:
out = open("類目.csv", "w", newline="")
except PermissionError:
print("文件被其他程序占用")
input("")
csv_writer = csv.writer(out, dialect="excel")
csv_writer.writerow(["寶貝ID", "類目"])
def open_chrome():
driver[0] = webdriver.Chrome()
driver[0].get("https://www.dianchacha.com")
input("請(qǐng)登陸后按回車:")
def EC_located(one_group, value):
"""
目的:簡化代碼長度,參數(shù)1選擇one或者group切換選中模式
:param value:要找的值【CSS選擇器】
:return:選擇到的對(duì)象
"""
wait = WebDriverWait(driver[0], 10)
if one_group == "one":
try:
ecl = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, value)))
return ecl
except TimeoutException:
print(value, "1元素未加載成功,等待超時(shí)")
else:
try:
ecl = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, value))
)
return ecl
except TimeoutException:
print(value, "1元素---組---未加載成功,等待超時(shí)")
def operating(ID):
# 先獲取ID輸入框
driver[0].get("https://www.dianchacha.com/item/info/index/iid/" + ID)
html = driver[0].page_source
if "未能找到親的寶貝" not in html:
colspans = EC_located("group", ".colspan-1")
colspan[0] = str(colspans[1].text).replace("寶貝類目: ", "")
else:
return operating(ID)
print(colspan)
def writer_txt():
csv_writer.writerow([url[0], colspan[0]])
print("保存", url[0], colspan[0], "成功")
url = ["0", "1"]
def main():
open_chrome()
file = "寶貝ID.txt"
with open(file) as f:
for line in f.readlines():
url[0] = line
print(line)
operating(url[0])
writer_txt()
out.close()
print("已完成")
if __name__ == "__main__":
main()
以上就是利用python 讀寫csv文件的詳細(xì)內(nèi)容,更多關(guān)于python 讀寫csv文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python中日期和時(shí)間格式化輸出的方法小結(jié)
這篇文章主要介紹了python中日期和時(shí)間格式化輸出的方法,實(shí)例總結(jié)了Python常見的日期與事件操作技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-03-03
利用Tkinter和matplotlib兩種方式畫餅狀圖的實(shí)例
下面小編就為大家?guī)硪黄肨kinter和matplotlib兩種方式畫餅狀圖的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望對(duì)大家有所幫助2017-11-11
python實(shí)現(xiàn)抽獎(jiǎng)小程序
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)抽獎(jiǎng)小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
python實(shí)現(xiàn)簡單的TCP代理服務(wù)器
這篇文章主要介紹了python實(shí)現(xiàn)簡單的TCP代理服務(wù)器,包含了完整的實(shí)現(xiàn)過程及對(duì)應(yīng)的源碼與說明文檔下載,非常具有參考借鑒價(jià)值,需要的朋友可以參考下2014-10-10
Python保存dict字典類型數(shù)據(jù)到Mysql并自動(dòng)創(chuàng)建表與列
這篇文章主要介紹了Python保存dict字典類型數(shù)據(jù)到Mysql并自動(dòng)創(chuàng)建表與列,字典是另一種可變?nèi)萜髂P?,且可存?chǔ)任意類型對(duì)象,想了解更多內(nèi)容的小伙伴可以和小編一起進(jìn)入下面文章學(xué)習(xí)更多內(nèi)容,希望對(duì)你有所幫助2022-02-02
import?sklearn報(bào)錯(cuò)正確安裝sklearn的解決方法
這篇文章主要介紹了import?sklearn報(bào)錯(cuò)正確安裝sklearn的解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04

