Python基础知识之文档

1.打开文档

在Python,使用open函数,可以打开一个已经存在的文件,或者创建一个新文件
open(文件名,访问模式)
示例如下:

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

在这里插入图片描述

2.关闭文件

close()
示例如下:
#新建一个文件,文件名为:test.txt
f=open(‘test.txt’,’w’)
#关闭这个文件
f.close()

3.写数据(write)

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

f=open('test.txt','w')
f.write('hello world ,i am here!')
#关闭这个文件
f.close()

4.读数据(read)

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

f=open('test.txt','r')
content=f.read(5)
print(content)
print("-"*30)
content=f.read()
print(content)
f.close()

结果: hello
------------------------------ world ,i am here!

注意:
如果open是打开一个文件,那么可以不用写打开的模式,即只写
open(‘test.txt’)
如果使用read读了多次,那么后面读取的数据是从上次读完后的位置开始的

5.读数据(readlines)

readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素。readlines()方法读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素,但读取大文件会比较占内存。

f=open('test.txt','r')
content=f.readlines()
print(type(content)) #<class 'list'>
print(content)#['hello world ,i am here!\n', 'world ,i am here!\n', 'i am here!']
i=1
for temp in content:
    print("%d:%s"%(i,temp))
    i+=1
f.close()

结果: 1:hello world ,i am here!

2:world ,i am here!

3:i am here!

6.读数据(readline)

从字面意思可以看出,该方法每次读出一行内容,所以,读取时占用内存小,比较适合大文件,该方法返回一个字符串对象。

f = open('test.txt', 'r')
content = f.readline()
print(content)#hello world ,i am here!
print("1:%s"%content)
content = f.readline()
print("2:%s"%content)
f.close()

结果:
1:hello world ,i am here!
2:world ,i am here!

7.linecache模块读取文

在python中,有个好用的模块linecache,该模块允许从任何文件里得到任何的行,并且使用缓存进行优化,常见的情况是从单个文件读取多行。
linecache.getlines(filename)
从名为filename的文件中得到全部内容,输出为列表格式,以文件每行为列表中的一个元素,并以linenum-1为元素在列表中的位置存储
linecache.getline(filename,lineno)
从名为filename的文件中得到第lineno行。这个函数从不会抛出一个异常–产生错误时它将返回”(换行符将包含在找到的行里)。如果文件没有找到,这个函数将会在sys.path搜索。
例子:

import linecache
f = open('test.txt', 'r')
a=linecache.getline('test.txt',2)
a  #Out[44]: 'world ,i am here!\n'
b=linecache.getlines('test.txt')[0:2]
b  #['hello world ,i am here!\n', 'world ,i am here!\n']
应用1:制作文件的备份

任务描述:输入文件的名字,然后程序自动完成对文件进行备份
步骤:
1.获取要复制的文件名 input()
2.打开这个文件(“r”)
3.创建一个文件xxx[复件].txt
4.从原文件中读取数据
5.将读取的数据写入到新文件中
6.关闭2个文件
参考代码:

oldFileName = input("请输入要拷贝的文件名字:")
oldFile = open(oldFileName,'r')
# 如果打开文件
if oldFile:
# 提取文件的后缀,rfind('.'),是获取从左边开始第一个‘.’的位置,oldFileName[fileFlagNum:]是切片
    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()
文件的随机读写:
#### (1)获取当前读写的位置
在读写文件的过程中,如果想知道当前的位置,可以使用tell()来获取
# 打开一个已经存在的文件
f = open("test.txt", "r")
str = f.read(5)
print("读取的数据是 : ", str)#读取的数据是 :  hello
# 查找当前位置
position = f.tell()
print ("当前文件位置 : ", position)#当前文件位置 :  5
str = f.read(3)
print ("读取的数据是 : ", str)#读取的数据是 :   wo
# 查找当前位置
position = f.tell()
print ("当前文件位置: ", position)#当前文件位置:  8
f.close()
(2)定位到某个位置

如果在读写文件的过程中,需要从另外一个位置进行操作的话,可以使用seek()
seek(offset,from)有2个参数
offset:偏移量
from:方向
0:表示文件开头
1:表示当前位置
2:表示文件末尾
把位置设置为:从文件开头,偏移4个字节

f = open("test.txt", "r")
str = f.read(30)
print("读取的数据是 : ", str)#读取的数据是 :  hello world ,i am here!
world 
# 查找当前位置
position = f.tell()
print ("当前文件位置 : ", position)#当前文件位置 :  31
#重新设置位置
f.seek(4,0)#Out[79]: 4
#查找当前位置
position = f.tell()
print ("当前文件位置 : ", position)#当前文件位置 :  4
f.close()
把位置设置为:离文件末尾,3字节处
f = open("test.txt", "rb")
str = f.read()
position = f.tell()
print ("当前文件位置 : ", position)#当前文件位置 :  54
f.seek(-3,2)
position = f.tell()
print ("当前文件位置 : ", position)#当前文件位置 :  51
f.close()

8.文件的重命名、删除

(1)文件重命名

os模块中的rename()可以完成对文件的重命名操作
rename(需要修改的文件名,新的文件名)

import os
os.rename("test[复件].txt", "test-最终版.txt")
(2)删除文件

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

import os
os.remove( "test-最终版.txt")

9.文件夹的相关操作:

(1)创建文件夹
import os
os.mkdir("Python学习")
(2)获取当前目录
import os
os.getcwd()
(3)改变默认目录
import os
os.chdir("../")
(4)获取目录列表
import os
os.listdir("./")
(5)删除文件夹
import os
os.rmdir("Python学习")

10 .应用:批量修改文件名

(1)运行过程演示

[‘学习1 - 副本 (2).txt’,
‘学习1 - 副本 (3).txt’,
‘学习1 - 副本 (4).txt’,
‘学习1 - 副本 (5).txt’,
‘学习1 - 副本 (6).txt’]
[Python]-学习1 - 副本 (2).txt
[Python]-学习1 - 副本 (3).txt
[Python]-学习1 - 副本 (4).txt
[Python]-学习1 - 副本 (5).txt
[Python]-学习1 - 副本 (6).txt

(2)参考代码

批量在文件名前加前缀

方法一
    import os
    os.chdir("C:\\Users\Administrator\\Desktop\\Python")
    os.getcwd()
    dirList=os.listdir()
    for name in dirList:
        print( name)
    os.rename(name, "[python]-"+name)
方法二
    import os
    funFlag = 1 # 1表示添加标志 2表示删除标志
    folderName = 'Python'
    # 获取指定路径的所有文件名字
    #os.getcwd()
    #os.chdir("C:\\Users\Administrator\\Desktop\\Python")
    dirList = os.listdir(folderName)
    # 遍历输出所有文件名字
    for name in dirList:
        #print( name)
        if funFlag == 1:
            newName = '[Python]-' + name
        elif funFlag == 2:
            num = len('[Python]-')
            newName = name[num:]
        print (newName)
        os.rename(folderName+"/"+name, folderName+"/"+newName)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值