1、 Open方法
- 使用with open()新建對象
- 寫入數(shù)據(jù)
# -*- coding: utf-8 -*-
# __author__ = 'Carina'
import requests
import os
from lxml import etree
url = "https://movie.douban.com/subject/26861685/comments"
r = requests.get(url).text
s = etree.HTML(r)
file = s.xpath('//div[@class="comment"]/p/text()')
# beforepath_ = os.getcwd() # 獲取當(dāng)前目錄
# after_path = os.chdir("C:/Users/Carina/Desktop") #修改目錄
# print(before_path)
# print(after_path)
# 使用open()保存
with open('C:/Users/Carina/Desktop/pinglun.txt', 'w', encoding='utf-8') as f: # 使用with創(chuàng)建對象
for i in file:
print(i)
f.write(i)
(1)open方法中可以寫上絕對路徑
(2)使用os庫腕铸,getcwd()查看當(dāng)前目錄,使用chdir()修改目錄
備注:open函數(shù)的打開模式
參數(shù) | 用法 |
---|---|
r | 只讀铛碑。若不存在文件會報錯狠裹。 |
w | 只寫。若不存在文件會自動新建汽烦。 |
a | 附加到文件末尾涛菠。 |
rb, wb, ab | 操作二進制 |
r+ | 讀寫模式打開 |
2、使用Pandas第三方庫
(1)保存數(shù)據(jù)到Excel
to_excel() :用于將DataFrame保存到Excel
#其中df為DataFrame結(jié)構(gòu)的數(shù)據(jù)撇吞,sheet_name = 'Sheet1'表示將數(shù)據(jù)保存在Excel表的第一張表中
df.to_excel('文件名.xlsx', sheet_name = 'Sheet1')
讀取Excel數(shù)據(jù)
read_excel() :從excel文件中讀取數(shù)據(jù)
pd.read_excel('文件名.xlsx', 'Sheet1', index_col=None, na_values=['NA'])
(2)保存數(shù)據(jù)到csv文件
- 導(dǎo)入相關(guān)的庫
- 將數(shù)據(jù)儲存為DataFrame對象
- 保存數(shù)據(jù)到csv文件
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,3)) #創(chuàng)建隨機值并保存為DataFrame結(jié)構(gòu)
print(df.head())
df.to_csv('file.csv') #可以是絕對路徑俗冻,若未指明就在當(dāng)前目錄下
提示:
如果運行以上程序出現(xiàn)ImportError: No module named ‘openpyxl’錯誤,需要安裝“openpyxl”模塊牍颈,openpyxl只能操作xlsx文件而不能操作xls文件迄薄。
(pip install openpyxl)
補充知識
1、在10分鐘了解pandas中可以快速了解和學(xué)習(xí)pandas的基本操作
2煮岁、閱讀csv模塊官方文檔讥蔽,了解使用csv模塊保存數(shù)據(jù)的方法