文件通常用于存储数据或应用系统的参数。Python 提供了 OSos.pathshuti等模块处理文件, 其中包括打开文件、 读写文件、 复制和删除文件等函数。

python文件操作基本流程:

 

1.打开文件,或者新建立一个文件

2.操作文件,如/写数据

3.关闭文件

 

6.1 文件的常见操作

6.1.1 文件的打开与关闭

文件句柄 = open('文件路径''模式')

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

    • r ,只读模式【默认】
    • w,只写模式【不可读;不存在则创建;存在则清空内容;】
    • x, 只写模式【不可读;不存在则创建,存在则报错】
    • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

    • r+, 读写【可读,可写】
    • w+,写读【可读,可写】
    • x+ ,写读【可读,可写】
    • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

    • rb  或 r+b
    • wb 或 w+b
    • xb 或 w+b
    • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

 

<1>打开文件

python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件

open(文件名,访问模式)

示例如下:

f = open('test.txt', 'w')

<2>关闭文件

close( )

示例如下:

# 新建一个文件,文件名为:test.txt
f = open('test.txt', 'w')

# 关闭这个文件
f.close()

6.1.2 文件的读写

 

<1>写数据(write)

使用write()可以完成向文件写入数据

demo:

f = open('test.txt', 'w')
f.write('hello world, i am here!')
f.close()

注意:

    • 如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

<2>读数据(read)

使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据

demo:

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

content = f.read(5)

print(content)

print("-"*30)

content = f.read()

print(content)

f.close()

 

注意:

如果open是打开一个文件,那么可以不用写打开的模式,即只写 open('test.txt')

如果使用读了多次,那么后面读取的数据是从上次读完后的位置开始的

<3>读数据(readlines

就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素

#coding=utf-8

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

content = f.readlines()

print(type(content))

i=1
for temp in content:
    print("%d:%s"%(i, temp))
    i+=1

f.close()

 

<4>读数据(readline

#coding=utf-8

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

content = f.readline()
print("1:%s"%content)

content = f.readline()
print("2:%s"%content)


f.close()

 

  文件的遍历可以使用循环的方式:

  

#coding=utf-8

f = open('test.txt', 'r')
for line in f:
print(line)
f.close()

示例:制作文件的备份

  任务描述

  

  • 输入文件的名字,然后程序自动完成对文件进行备份

 

# --*-- coding=utf-8 --*--

oldFileName = input("请输入要拷贝的文件名字:")

oldFile = open(oldFileName,'r')
# 如果打开文件if oldFile:

# 提取文件的后缀
fileFlagNum = oldFileName.rfind('.')
if fileFlagNum > 0:
    fileFlag = oldFileName[fileFlagNum:]

# 组织新的文件名字
newFileName = oldFileName[:fileFlagNum] + '[复件]' + fileFlag

# 创建新文件
newFile = open(newFileName, 'w')

# 把旧文件中的数据,一行一行的进行复制到新文件中
for lineContent in oldFile.readlines():
    newFile.write(lineContent)

# 关闭文件
oldFile.close()
newFile.close()
View Code

6.1.3 文件的随机读写

 

<1>获取当前读写的位置

 

在读写文件的过程中,如果想知道当前的位置,可以使用tell()来获取

# 打开一个已经存在的文件
f = open("test.txt", "r")
str = f.read(3)
print("读取的数据是 : ", str)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

str = f.read(3)
print("读取的数据是 : ", str)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

f.close()
View Code

 

 

<2>定位到某个位置

 

如果在读写文件的过程中,需要从另外一个位置进行操作的话,可以使用seek()

 

seek(offset, from)有2个参数

 

offset:偏移量

 

from:方向

 

0:表示文件开头

 

1:表示当前位置

 

2:表示文件末尾

 

demo:把位置设置为:从文件开头,偏移5个字节

 

# 打开一个已经存在的文件
f = open("test.txt", "r")
str = f.read(30)
print("读取的数据是 : ", str)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

# 重新设置位置
f.seek(5,0)

# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

f.close()
View Code

 

 

demo:把位置设置为:离文件末尾,3字节处

 

# 打开一个已经存在的文件
# f = open("test.txt", "r")
# 程序运行报错io.UnsupportedOperation: can't do nonzero cur-relative seeks
# 修改为:
f = open("test.txt", "rb")


# 查找当前位置
position = f.tell()
print("当前文件位置 : ", position)

# 重新设置位置
f.seek(-3,2)

# 读取到的数据为:文件最后3个字节数据
str = f.read().decode()

print("读取的数据是 : ", str)

f.close()
View Code

6.1.4 文件的重命名、删除

 

有些时候,需要对文件进行重命名、删除等一些操作,python的os模块中都有这么功能

<1>文件重命名

os模块中的rename()可以完成对文件的重命名操作

rename(需要修改的文件名, 新的文件名)

import os

os.rename("毕业论文.txt", "毕业论文-最终版.txt")

<2>删除文件

os模块中的remove()可以完成对文件的删除操作

remove(待删除的文件名)

import os

os.remove("毕业论文.txt")

 

6.2 文件夹的相关操作

实际开发中,有时需要用程序的方式对文件夹进行一定的操作,比如创建、删除等

就像对文件操作需要os模块一样,如果要操作文件夹,同样需要os模块

<1>创建文件夹

import os

os.mkdir("张三")

<2>获取当前目录

import os

os.getcwd()

<3>改变默认目录

import os

os.chdir("../")

<4>获取目录列表

import os

os.listdir("./")

<5>删除文件夹

import os

os.rmdir("张三")

 

示例:应用【面试题】:批量修改文件名

源文件:

 

[root@rs1 renameDir]# ll
总用量 0
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-1.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-2.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-3.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-4.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-5.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-6.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-7.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-8.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 新三国-9.txt

 

修改后的文件:

[root@rs1 enameDir]# ll
总用量 0
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-1.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-2.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-3.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-4.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-5.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-6.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-7.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-8.txt
drwxr-xr-x 2 root root 6 9月 24 17:17 [英皇出品]-新三国-9.txt

#coding=utf-8

# 批量在文件名前加前缀

import os

funFlag = 1 # 1表示添加标志  2表示删除标志

folderName = './renameDir/'

# 获取指定路径的所有文件名字
dirList = os.listdir(folderName)

# 遍历输出所有文件名字
for name in dirList:
    print name

    if funFlag == 1:
        newName = '[英皇出品]-' + name
    elif funFlag == 2:
        num = len('[英皇出品]-')
        newName = name[num:]
    print newName

    os.rename(folderName+name, folderName+newName)
View Code

6.3 文件内容的搜索和替换

文件内容的搜索和替换可以结合前面学习的字符串查找和替换来实现。例如,从 hello.txt 文件中查找字符串 “hello” ,并统计 “hello” 出现的次数。 hello.txt 文件如下所示。

1 hello world

3 hello hello China

下面这段代码从 hello.txt 中统计字符串 “hello” 的个数。

#文件的查找
import re
f1 = open('hello.txt')
count = 0
for s in f1.readlines():
    li = re.findall('hello',s)
    if len(li) > 0:
        count = count + li.count('hello')

print("查找到"+ str(count) + "个hello")
f1.close()

【代码说明】

口第 5行代码定义变量count,用于计算字符串 “hello” 出现的次数。

口第 6行代码每 次从文件 hello .txt中读取1行到变量。

口第7行代码调用re 模块的函数findall()查询变量s, 把查找的结果存储到列表li中。

口第8行代码, 如果列表中的元素个数大于0,则表示查找到字符串 “hello” 。

口第9行代码调用列 表的count()方法, 统计当前列表中 "hello"出现的次数。

口第10行代码输出结果:

下面这段代码把 hello .txt 中的字符串 “hello” 全部替换为 “hi” ,并把结果保持到文件hello2.txt中。

# 文件的替换
f1 = open("hello.txt")
f2 = open("hello2.txt","w")
for s in f1.readlines() :
    f2.write(s.replace('hello','hi'))
f1.close()
f2.close()

 

5行代码 先使用replace()把变量s中的“hello”替换为“hl,然后把结果写入到hello2.txt

中。 文件 hello2.txt的内容如下所示。

 

管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:
    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
    pass

作业:

文件test.txt中包含以下内容:

今年是2017年。

2017年你好。

2017年再见

1) 读取该文件,并输出所有内容。

2) 去掉文件内容中的换行。

3) 计算出文件的长度。

4 )使用欧冠2018替换 2017。

5 )创建另一个文件test2.txt, 写入本文件的内容。

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!