def read_all(txt):
...: with open(txt,'r') as f:
...: return f.read()
...:
read_all('test.txt')
Out[23]: 'a,b,c,d\ne,f,g,h\ni,j,k,l\n'
按行讀取txt文件內(nèi)容
def read_line(txt):
...: line_list = []
...: with open(txt,'r') as f:
...: for line in f.readlines():
...: line_list.append(line)
...: return line_list
...:
read_line('test.txt')
Out[27]: ['a,b,c,d\n', 'e,f,g,h\n', 'i,j,k,l\n']
保存文件
直接保存字符串。
str = 'aaaabbbbcc'
with open('test.txt','w') as f:
...: f.write(str)
...:
with open('test.txt','r') as f:
...: print(f.read())
...:
aaaabbbbcc
將列表中內(nèi)容寫入txt文件。
直接寫入
data = ['a','b','c']
...: with open("data.txt","w") as f:
...: f.writelines(data)
...:
with open('data.txt','r') as f:
...: print(f.read())
...:
abc
按行寫入。
data = ['a','b','c']
with open('data.txt','w')as f:
...: for i in data:
...: i = str(i)+'\n'
...: f.write(i)
with open('data.txt','r') as f:
...: print(f.read())
...:
a
b
c
CSV文件
讀取csv文件
使用python內(nèi)置csv讀取.csv文件內(nèi)容。
import csv
with open('test.csv', 'r') as f:
data = csv.reader(f)
print(next(data))
['filename', 'label']
寫入csv文件
使用python內(nèi)置csv寫入.csv文件。
import csv
with open('data.csv', 'w')as file:
dtwt = csv.writer(file)
dtwt.writerow(['世', '間', '美', '好', '與', '你', '環(huán)環(huán)', '相', '扣'])
import csv
with open('data.csv', 'r') as f:
data = csv.reader(f)
print(next(data))