基本存储:存储至TXT或CSV
把数据存储至TXT
title = "This is the test sentence"
# 第一种保存方法
with open('D:\\python\\pythonItem\\Scrapy\\UNIT6\\1.基本存储:存储TXT和CSV\\title.txt', "a+") as f: # 把D:\\...换成自己保存的地址
f.write(title)
f.close()
# 第二种保存方法
with open(r'D:\python\pythonItem\Scrapy\UNIT6\1.基本存储:存储TXT和CSV\title2.txt', "a+") as f:
f.write(title)
f.close()
几种打开文件的方式
读写方式 | 可否读写 | 若文件不存在 | 写入方式 |
---|---|---|---|
w | 写入 | 创建 | 覆方式 |
w+ | 读取+写入 | 创建 | 覆盖方式 |
r | 读取 | 报错 | 不可写入 |
r+ | 读取+写入 | 报错 | 覆盖写入 |
a | 写入 | 创建 | 附加写入 |
a+ | 读取+写入 | 创建 | 附加写入 |
存储地址可以有以下三种方式:
(1)with open(‘C:\\you\\desktop\\title.txt’, “a+”) as f:
(2)with open(r’C:\you\desktop\title.txt’, “a+”) as f:
(3)with open(‘C:/you/desktop/title.txt’, “a+”) as f:
把数据存储至CSV
import csv
# 读取CSV文件
with open(r'D:\python\pythonItem\Scrapy\UNIT6\1.基本存储:存储TXT和CSV\test.csv', "r", encoding='UTF-8') as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
print(row) # 依次读取
print(row[0])
# 写入CSV文件
output_list = ['1', '2', '3', '4'] # 将写入的变量加入到列表中
with open('test2.csv', 'a+', encoding='UTF-8', newline='') as csvfile:
w = csv.writer(csvfile)
w.writerow(output_list) # 把一个列表直接写入到一列中