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文件内容
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
将列表中内容写入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内置csv读取.csv文件内容。
import csv
with open('test.csv', 'r') as f:
data = csv.reader(f)
print(next(data))
['filename', 'label']
写入csv文件
使用python内置csv写入.csv文件。
import csv
with open('data.csv', 'w')as file:
dtwt = csv.writer(file)
dtwt.writerow(['世', '间', '美', '好', '与', '你', '环环', '相', '扣'])
import csv
with open('data.csv', 'r') as f:
data = csv.reader(f)
print(next(data))