把python is a tool写入到a.txt
with open("a.txt", "w") as f:
f.write(str("python is a tool"))
with open("a.txt", "r") as f:
data = f.read()
print(data)
with open("a.txt", "r") as f:
data = f.readLine()
print(data)
with open("a.txt", "r") as f:
data = f.readLines()
print(data)
如果a.txt中是多行数据的话,data打印出来是列表
使用strip()方法来去除换行符
with open("a.txt", "r") as f:
data = f.readLines()
for line in data:
print(line.strip('\n'))
import csv
# csv的文件头
fileHeader = ['name', 'age', 'score']
# csv的数据
d1 = ['小明', 20, 90]
d2 = ['小李', 18, 89]
d3 = ['小王', 21, 91]
# 写入数据
csvFile = open("b.csv", "w", newline = "")
writer = csv.writer(csvFile)
# 以列表的形式传入函数
writer.writerow(fileHeader)
writer.writerow(d1)
writer.writerow(d2)
writer.writerow(d3)
csvFile.close()
csv中的数据如下
name | age | score |
---|---|---|
小明 | 20 | 90 |
小李 | 18 | 89 |
小王 | 21 | 91 |
import csv
# csv的文件头
fileHeader = ['name', 'age', 'score']
# csv的数据
d1 = ['小明', 20, 90]
d2 = ['小李', 18, 89]
d3 = ['小王', 21, 91]
# 写入数据,把w改成a,就可以实现追加写
csvFile = open("b.csv", "w", newline = "")
writer = csv.writer(csvFile)
# 每次写入多个列表
writer.writerows([fileHeader, d1, d2, d3])
csvFile.close()
csv中的数据如下
name | age | score |
---|---|---|
小明 | 20 | 90 |
小李 | 18 | 89 |
小王 | 21 | 91 |
import csv
# csv的文件头
fileHeader = ['name', 'age', 'score']
# DictWriter设置以字典形式写csv,这里也设置了表头fileHeader,但是还没把表头写入csv
writer = csv.DictWriter(csvFile, fileHeader)
# 将表头写入csv,writeheader()方法没有参数,是因为上一步已经在DictWriter()里设定了表头参数fileHeader
writer.writeheader()
# 将数据以字典的形式写入csv
writer.writerow({"name":"小明", "age": 20, "score": 90})
writer.writerow({"name":"小李", "age": 18, "score": 89})
writer.writerow({"name":"小王", "age": 21, "score": 91})
csvFile.close()
csv中的数据如下
name | age | score |
---|---|---|
小明 | 20 | 90 |
小李 | 18 | 89 |
小王 | 21 | 91 |
第二种方式写表头
import csv
# csv的文件头
fileHeader = ['name', 'age', 'score']
# DictWriter设置以字典形式写csv,这里也设置了表头fileHeader,但是还没把表头写入csv
writer = csv.DictWriter(csvFile, fileHeader)
# 第二种方式 将表头写入csv
writer.writerow(dcit(zip(fileHeader, fileHeader)))
# 将数据以字典的形式写入csv
writer.writerow({"name":"小明", "age": 20, "score": 90})
writer.writerow({"name":"小李", "age": 18, "score": 89})
writer.writerow({"name":"小王", "age": 21, "score": 91})
csvFile.close()
name | age | score |
---|---|---|
小明 | 20 | 90 |
小李 | 18 | 89 |
小王 | 21 | 91 |
import csv
csvFile = open("b.csv", "r")
csvReader = csv.DictReader(csvFile)
print(csvReader.fieldnames)
打印出来是列表[‘name’, ‘age’, ‘score’]
import csv
csvFile = open("b.csv", "r")
csvReader = csv.DictReader(csvFile)
for row in csvReader:
print(row)
打印出来是
{‘name’:‘小明’,‘age’:‘20’, ‘score’:‘90’}
{‘name’:‘小李’,‘age’:‘18’, ‘score’:‘89’}
{‘name’:‘小王’,‘age’:‘21’, ‘score’:‘91’}