Python 基础打卡5

Python 基础打卡51.filea.打开文件方式(读写两种方式)b.文件对象的操作方法c.学习对excel及csv文件进行操作csv文件操作Excel文件操作2.os模块3.datetime模块4.类和对象5.正则表达式6.re模块7.http请求参考:https://blog.csdn.net/weixin_33705053/article/details/872090361.file...
摘要由CSDN通过智能技术生成


参考: https://blog.csdn.net/weixin_33705053/article/details/87209036
https://blog.csdn.net/hxy199421/article/details/81033229
https://blog.csdn.net/colourful_sky/article/details/80160340
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

1.file

a.打开文件方式(读写两种方式)

open()打开文件
file_object = open(file_name [, access_mode][, buffering])

参数 描述
file_name 访问文件的路径名
access_mode 打开文件的模式,默认为只读
buffering 是否缓冲 (0=不缓冲,1=缓冲,<0缓存区为系统默认值,>1的int数=缓冲区大小)

文件打开模式:

模式 描述
r 只读
w 只写 (会清空原始内容)
a 追加
rb 以二进制模式打开,只读
wb 以二进制模式打开,只写
r+ 读和写
w+ 消除文件内容,之后可以读和写
a+ 追加,读和写

read()读取文件
有三种读取形式

读取形式 描述
file_object.read() 读取整个文件
file_object.readline() 读取一行
file_object.readlines() 读取文件的所有行,并自动将文件解析为一个行列表

for语句遍历read()读取的数据,再通过print()输出

write()写入文件
file_object.write(‘str’),str是要写入的字符串内容
file_object.writelines(list),把list中的字符串按行写入文件,连续写入,无换行
【写入多行,需要换行可以在写入的字符串最后加 \n】

close()关闭文件
文件读取完毕后,需要关闭文件,file_object.close()

小实验1:

#读取TXT文件
#要打开的文件与当前程序文件处于同一目录下
with open('haiTest.txt') as file_object:
#查找文件路径
#with open('E:\learning\python\jupyter\pyBase\haiTest.txt') as file_object:       
    contents = file_object.read()
    print(contents)
#输出:Yesterday is history, tomorrow is a mystery, but today is a gift. 

file_object = open('haiTest.txt')
contents = file_object.read()
print(contents)
#输出:Yesterday is history, tomorrow is a mystery, but today is a gift. 
b.文件对象的操作方法
操作方法 描述
file_object.fileno() 获得文件描述符,是一个数字
file_object.flush() 刷新输出缓存
file_object.isatty() 文件是否为交互终端,返回True/False
file_object.seek(offset[,where]) 文件指针移动到相对于where的offset的位置
file_object.tell() 获取文件指针位置
file_object.truncate([size]) 截取文件(size为大小)
file_object.name 返回文件名
file_object.mode 返回文件读取形式
c.学习对excel及csv文件进行操作
csv文件操作

打开CSV
需要提前导入CSV函数包— import csv
打开csv: csv_file=open(file_name[, access_mode])
读取CSV
读取csv: csv_file=csv.reader(csvfile);pandas.read_csv(file_name)[导入pandas库](读取后返回的是文件的内存地址)
写入CSV
实例化一个write对象: csv_writer = write(csv_file)
利用writerow函数写入: csv_writer.writerow(“new_information”)

小实验1:

import csv
csvfile = open('student.csv', encoding = 'utf-8')
data = csv.reader(csvfile)  #data 返回内存地址
for line in data: 
    print (line)

输出:

['\ufeff学号', '年龄'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值