Python语法学习四之IO操作

一、文件操作

1-1、打开/创建文件

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

open(文件名,访问模式)

f = open('C:/Users/cehae/Desktop/test.txt', 'w')

访问模式


3163615-86abc6b782b8be69.png
图片.png
1-2、关闭文件

close( )

f = open('C:/Users/cehae/Desktop/test.txt', 'r')
# 关闭文件
f.close()
1-3、写入文件

使用write()可以完成向文件写入数据
如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

f = open('C:/Users/cehae/Desktop/test.txt', 'w')

f.write('hello world, i am here!')

f.close()
1-4、读取文件
1-4-1、read读取数据

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

注意:

  • 如果open是打开一个文件,那么可以不用谢打开的模式,即只写 open('test.txt')
  • 如果使用读了多次,那么后面读取的数据是从上次读完后的位置开始的
f = open('C:/Users/cehae/Desktop/test.txt', 'r')

content = f.read(5)

print(content)

print("-" * 30)

content = f.read()

print(content)

f.close()
3163615-cb672962f8ae76c8.png
图片.png
3163615-f0cc5e87b75c62fa.png
图片.png
1-4-2、readlines读取

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

f = open('C:/Users/cehae/Desktop/test.txt', 'r')
content = f.readlines()
print(type(content))
i = 1
for temp in content:
    print("第%d行: %s" % (i, temp))
    i += 1

f.close()
3163615-50603e75b148f427.png
图片.png
1-4-3、readline读取

一次读取一行

f = open('C:/Users/cehae/Desktop/test.txt', 'r')

print("readline 第1行: %s" % f.readline())
print("readline 第2行: %s" % f.readline())

f.close()
3163615-0c7c3207acc22201.png
图片.png
1-5、文件读写定位
1-5-1、获取当前读写的位置

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

f = open('C:/Users/cehae/Desktop/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()
3163615-29727667b32e739b.png
图片.png
1-5-2、定位到某个位置

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

seek(offset, from)有2个参数:

  • offset:偏移量

  • from:方向:

    • 0:表示文件开头
    • 1:表示当前位置
    • 2:表示文件末尾
f = open('C:/Users/cehae/Desktop/test.txt', 'r')

# 把位置设置为:从文件开头,偏移5个字节
str = f.read(10)
print "读取的数据是 : ", str

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

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

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

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

f.close()
3163615-ec0aa05a5932a3db.png
图片.png
1-6、文件重命名

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

    import os
    os.rename("毕业论文.txt", "毕业论文-最最最终版.txt")
1-7、文件重删除

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

    import os
    os.remove("毕业论文-最最最终版.txt")

二、文件夹操作

实际开发中,有时需要用程序的方式对文件夹进行一定的操作,比如创建、删除等。就像对文件操作需要os模块一样,如果要操作文件夹,同样需要os模块

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

猜你喜欢

转载自blog.csdn.net/weixin_33735676/article/details/87518283
今日推荐