文件
打开文件
要打开文件,可使用函数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
更多的方法可以查表