首先来看看原始的读取:
f= open(file,‘r‘) stat = f.readlines() print(stat)
输出的结构是一个整体的列表。
[‘姓名,性别,年龄,爱好,人脉,学习\n‘, ‘0,8,0,9,0\n‘, ‘1,9,1,10,1\n‘, ‘2,10,4,11,2\n‘, ‘3,11,9,12,3\n‘, ‘4,12,16,13,4\n‘, ‘5,13,25,14,5\n‘, ‘6,14,36,15,6\n‘, ‘7,15,49,16,7\n‘, ‘8,16,64,17,8\n‘, ‘9,17,81,18,9\n‘, ‘10,18,100,19,10\n‘, ‘11,19,121,20,11\n‘‘]
采用csv模块操作,能更方便的进行数据的操作:
with open(file,‘r‘) as file: reader = csv.reader(file) lines = [line for line in reader] print(lines)
[[‘姓名‘, ‘性别‘, ‘年龄‘, ‘爱好‘, ‘人脉‘, ‘学习‘], [‘0‘, ‘8‘, ‘0‘, ‘9‘, ‘0‘], [‘1‘, ‘9‘, ‘1‘, ‘10‘, ‘1‘], [‘2‘, ‘10‘, ‘4‘, ‘11‘, ‘2‘], [‘3‘, ‘11‘, ‘9‘, ‘12‘, ‘3‘], [‘4‘, ‘12‘, ‘16‘, ‘13‘, ‘4‘], [‘5‘, ‘13‘, ‘25‘, ‘14‘, ‘5‘], [‘6‘, ‘14‘, ‘36‘, ‘15‘, ‘6‘]]
一、csv的写操作:
import csv csvflie= open(file,‘w‘,newline=‘‘) #newline指的是文件的最后none--->\n try: writer = csv.writer(csvfile)#构建一个写的对象 print(type(writer)) writer.writerow=((‘姓名‘,‘行呗‘,‘学号‘))#往里面写数据 for i in range(10): writer.writerow=((i,i+1,i*i))#注意切记!无等号 print(‘chengg‘) except Exception as c: print(c) print(‘操作失败‘) finally: csvfile.close()
1.1查看文件的大小
def get_size(path): file_size = os.path.getsize(path) print(file_size) get_size(file)
二、csv文件的读取操作
方法一:用index索引重新写入
import csv with open(file,‘r‘) as file: reader = csv.reader(file) rows =[row for row in reader] #把reader遍历在一个列表中 for line in rows: print(line) for index,i in enumerate(line):#把每个元素取出来 with open(r‘C:\Users\jeep-peng zhang\Desktop\demo.txt‘,‘a‘) as file_new: if index==len(line)-1:#换行 file_new.write(i+‘\n‘) else: file_new.write(i+‘ ‘) file_new.close()
方法二:
import csv with open(file,‘r‘) as file: reader = csv.reader(file) lines = [line for line in reader]#循环把他存在列表里面 for result in lines:#把列表里面的东西循环出来 line_str = ‘,‘.join(result)#用逗号隔开 print(line_str) with open(r‘C:\Users\jeep-peng zhang\Desktop\demo.txt‘,‘a‘) as new_file: # writer = csv.writer(new_file) # writer.row(line_str+‘\n‘) new_file.write(line_str+‘\n‘)