前言
一.Python文件读取二、读取CSV文件
打开文件之后就要开始操作了,一个读取了,但是要是没有打开文件就会报错,或则在读取的过程中报错就不会关闭文件了,所以为了无论报错与否,在使用完文件后就要关闭文件。如下:
try: f = open('/path/to/file', 'r') print(f.read()) finally: if f: f.close()这样写太过于麻烦,Python中直接使用with来直接自动来帮我们调用close()
with open('/path/to/file', 'r') as f: print(f.read())上面的写法和try...finally效果一样。
f.read()一次性读入所有数据,保险起见可以规定每次读取的数据大小,f.read(size)进行反复调用读取。
f.readline(),每次读取一行,f.readlines()一次读取多行另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。
for line in f.readlines(): print(line.strip()) # 把末尾的'\n'删掉和写文件一样,首先使用open函数直接打开但是传入标识符mode='w'即写入模式。 可以调用f.write()写入内容,写完之后务必使用f.close()关闭文件。
方法一: f = open('/Users/michael/test.txt', 'w') f.write('Hello, world!') f.close() 方法二: with open('/Users/michael/test.txt', 'w') as f: f.write('Hello, world!') 要写入或则是读取特定编码的文本文件,请给open()函数传入encoding参数,将字符串自动转换成指定编码。
1.获取csv文件的文件表头
#方式一 import csv with open("D:\\test.csv") as f: reader = csv.reader(f) rows=[row for row in reader] print(rows[0]) #方式二 import csv with open("D:\\test.csv") as f: #1.创建阅读器对象 reader = csv.reader(f) #2.读取文件第一行数据 head_row=next(reader) print(head_row)2.读取文件的某一列数据
说明使用csv.reader()返回一个reader对象,它将迭代给定csvfile中的行。 csvfile可以是任何支持迭代器协议的对象, 并在每次__next__()调用其方法时返回一个字符串- 文件对象和列表对象都是合适的。 import csv with open("D:\\test.csv") as f: reader = csv.reader(f) column=[row[0] for row in reader] print(column)3.写入csv文件
import csv with open("D:\\test.csv",'a') as f: row=['曹操','23','学生','黑龙江','5000'] write=csv.writer(f) write.writerow(row) print("写入完毕!") writerow()方法是一行一行写入,writerows方法是一次写入多行1.读取csv的全部文件
import pandas as pd path= 'D:\\test.csv' with open(path) as file: data=pd.read_csv(file) print(data)2.读取文件前几行数据
import pandas as pd path= 'D:\\test.csv' with open(path)as file: data=pd.read_csv(file) #读取前2行数据 head_datas = data.head(0) head_datas = data.head(1) print(head_datas) 说明head函数就是用来读取哪一行的3.读取文件哪一行的全部内容
import pandas as pd path= 'D:\\test.csv' with open(path)as file: data=pd.read_csv(file) #读取第一行所有数据 print(data.ix[0,])4.读取文件的哪几行数据
import pandas as pd path= 'D:\\test.csv' with open(path)as file: data=pd.read_csv(file) #读取第一行、第二行、第四行的所有数据 print(data.ix[[0,1,3],:])5.读取所有行和列数据
import pandas as pd path= 'D:\\test.csv' with open(path)as file: data=pd.read_csv(file) #读取所有行和列数据 print(data.ix[:,:])转载于:https://www.cnblogs.com/tsruixi/p/11395160.html
