python的文件与文件系统

文件

打开文件
要打开文件,可使用函数open,它位于自动导入的模块io中。函数open将文件名作为唯一必不可少的参数,并返回一个文件对象。如果当前目录中有一个somefile.txt的文本文件,则可像下面这样打开它:

 f = open('somefile.txt')

如果文件位于其他地方,可指定完整的路径。如果指定的文件不存在,将看到类似于下面的异常:

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'somefile.txt'

不同打开文件的方式
在这里插入图片描述
文件操作的各类方法
somefile.txt:
Welcome to this file
There is nothing here except
This stupid haiku

1.read

>>> f = open(r'C:\text\somefile.txt')
>>> f.read(7)#读取7个字符
'Welcome'
>>> f.read(4)
' to '
>>> f.close() 
>>> f = open(r'C:\text\somefile.txt')
>>> print(f.read())
Welcome to this file
There is nothing here except
This stupid haiku
>>> f.close()

2.readline

#readline能够读取一整行的内容
>>> f = open(r'C:\text\somefile.txt')
>>> for i in range(3):
 print(str(i) + ': ' + f.readline(), end='')
0: Welcome to this file
1: There is nothing here except
2: This stupid haiku
>>> f.close() 

3.write

>>> f = open(r'C:\text\somefile.txt', 'w')
>>> f.write('this\nis no\nhaiku')
13
>>> f.close() 

4.tell
方法 tell()返回当前位于文件的什么位置

文件系统

os模块
在python中对于文件系统的访问一般使用的是os模块。python是跨平台的,因此在使用os模块时,不需要关心是在什么系统下使用的
1.access() 函数:
os.access() 方法使用当前的uid/gid尝试访问路径。

import os
 
FilePath = os.access("F:\\python\\test_file.txt",os.F_OK) #必须带有文件的后缀名
 
print("文件夹下是否存在指定文件:",FilePath)
 
#上面代码的输出结果为:文件夹下是否存在指定文件: True

2.os.getcwd()函数:
os.getcwd()方法用于返回当前工作目录。

import os
print(os.getcwd())
#上面代码的输出结果为:F:\Pycharm_project\Demo\demo

更多的方法可以查表
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值