python文件处理相关知识

一、读文件

1. open函数

在这里插入图片描述

2. with … as …

在这里插入图片描述

这种读取文件的方法更加合理,因为不需要考虑打开的文件是否关闭。

3. read的方法

# 1. Read certain amount of characters

with open(example1, "r") as file1:
    print(file1.read(16))
    print(file1.read(5))
    print(file1.read(9))

# 2. Read one line

with open(example1, "r") as file1:
    print("first line: " + file1.readline())

# 3. Iterate through the lines

with open(example1,"r") as file1:
        i = 0
        for line in file1:
            print("Iteration", str(i), ": ", line)
            i = i + 1

# 4. Read all lines and save as a list

with open(example1, "r") as file1:
    FileasList = file1.readlines()

二、写文件

写和读的没有差别,我们重点介绍下读写的模式。

  • r+ : Reading and writing. Maybe useful to add a .truncate() method at the end of your data.
  • w+ : Writing and reading.
  • a+ : Appending and Reading.

在同时读写文件中,游标的概念很重要。write是直接在new file头开始写,而append是在打开文件的尾巴开始写。read是从当前游标开始向后读。

控制游标的函数:

  • .tell() - returns the current position in bytes 返回当前游标位置
  • .seek(offset,from) - changes the position by ‘offset’ bytes with respect to ‘from’. From can take the value of 0,1,2 corresponding to beginning, relative to current position and end

举例一下就知道怎么回事了:

with open('Example2.txt', 'a+') as testwritefile:
    print("Initial Location: {}".format(testwritefile.tell()))
    
    data = testwritefile.read()
    if (not data):  #empty strings return false in python
            print('Read nothing') 
    else: 
            print(testwritefile.read())
            
    testwritefile.seek(0,0) # move 0 bytes from beginning.
    
    print("\nNew Location : {}".format(testwritefile.tell()))
    data = testwritefile.read()
    if (not data): 
            print('Read nothing') 
    else: 
            print(data)
    
    print("Location after read: {}".format(testwritefile.tell()) )

output:

Initial Location: 70
Read nothing

New Location : 0
Overwrite
This is line C
This is line D
This is line E
This is line E

Location after read: 70
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值