python文件操作

文件读取

1、读取是将磁盘中的数据读取到内存中的变量中

  • 不写模式,默认是读取
  • 开始时定义在文件头,每读取一次,向后移动指定字符数
f = open('log/test.txt','r',encoding='utf-8')  # 
lines = f.readlines()
f.close()

所有内容保存在一个列表中,每行作为列表中的一个元素,末尾有\n

若不要\n,输出时加个end = ''

结果:['Site 1: P147-1\n', 'Testflow started on 11/16/21 at 05:16:37\n', '\n', 'Site  TNum      Test  TestSuite  p/f      Pin  LoLim  Measure  HiLim  \n']

2、其他读取

something = f.read(3)   # 读取成字符串,数字代表读取几个字符,不指定则读全部
something = f.readline()    #

3、读取后的操作,去掉\n,指定分割符

for line in lines:
# 原始数据每行结尾有个\n,要去掉  #还原了原始数据
line = line.replace('\r','').replace('\n','').replace('<=','').replace('\t','')
line = x.strip('\n').split(',')  # 或者这样

4、读取成字典

alldata = {}       
for x in datalines:
line = x.strip('\n').split(',')
name = line[0]  
pwd = line[1]   
state = line[2] 
num = int(line[3]) 
alldata[name] = [pwd,state,num]
print(alldata)

结果:{'user': ['password', 'state', 0], 'admin': ['123', 'unlock', 1], '张三': ['456', 'lock', 2], '李四': ['321', 'lock', 3]}

文件追加

	content='root123unlock2'
	f=open('demo.txt','a')
	f.write('\n'+content)
# f.write不能写列表,会报错;f.writelines可以加列表,但是列表元素间没有空格,不允许写整数

文件写

当模式为w时,若文件不存在会新建

文件重命名

import os
os.rename('data','data1')

文件删除

os.remoove()

if__name__=='__main__' 解释

1、Python是动态的逐行解释运行,从脚本的第一行运行,没有统一的入口。

2、模拟程序入口,当被引用时,不会执行原来文件的主函数。

3、__name__等于模块名称  __main__等于当前执行文件的名称

加了此语句后只有当文件作为脚本直接执行时,该语句后的内容才会被执行,而import到其他脚本中是不会被执行的。

字典

chips[chip_key]=chip_rows.copy()

# chips = {chip_key: chip_rows.copy()}  # 同种写法

chips是字典,chip_key是字符串,chip_rows是列表

 打印出来的结果

{'P147-1': [<__main__.ChipRowData object at 0x0000000005220220>,

<__main__.ChipRowData object at 0x0000000005220250>,

<__main__.ChipRowData object at 0x0000000005220280>,

<__main__.ChipRowData object at 0x00000000052202B0>,

<__main__.ChipRowData object at 0x00000000052202E0>,

<__main__.ChipRowData object at 0x0000000005220310>,

<__main__.ChipRowData object at 0x0000000005220340>,

<__main__.ChipRowData object at 0x0000000005220370>]}

异常

比如打开一个文件不存在,明知道会有问题,却不处理

try:        

    wb=openpyxl.load_workbook('test.xlsx')

except:     

        print('文件不存在')

将所有可能出现的异常都写出来

try:

    f = open('a.txt',r)

    print(num)

except(NameError,IOError):

    print('出现错误了')

打印出错误信息

try:

    f=open('a.txt','r')

    print(num)

except(NameError,IOError) as result:

    print('出现错误了')

    print(result)

捕获所有异常

try:

    f=open('a.txt','r')

    print(num)

except Exception as result:

    print('出现错误了')

    print(result)

try catch finally

try:

    f=open('data1','r',encoding='utf-8')

    try:

        whileTrue:

        content=f.readline()

        iflen(content)==0:#没有内容

        break

time.sleep(2)#休眠两秒

print(content)

finally:

f.close()#保证文件关闭,不管是否发生异常

print('文件关闭')

exceptExceptionasresult:

print('文件异常')

print(result)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值