计算机二级:文件操作
文件操作
文章目录
- 文件操作
- 文件的打开与关闭
- 文件的打开
- 文件对象的其它方法
- 文本文件的操作
- 文本文件的读取
- 文本文件的写入
- 二进制文件操作
- 文件的定位
- 文件处理
- 重命名
- 文件删除
- 目录操作
- 1. `os.mkdir()`
- 2. `os.chdir()`
- 3. `os.getcwd()`
- 4. `os.rmdir()`
文件的打开与关闭
文件的打开
文件的打开使用open
函数:
文件对象=open(文件说明符[,打开方式][,缓冲区])
对于文件的打开方有:r,w,a,b,+
b
:代表的是二进制文件r
:代表读文件a
:代表续写w
:代表写文件+
:代表读和写
值得注意的是:w
是覆盖式或创建式地创建,a
代表续写.
文件对象的其它方法
方法名 | 描述 | 示例 |
---|---|---|
close() | 关闭文件。关闭后,不能再对文件进行读写操作。通常在文件使用完毕后调用,以释放系统资源。 | python<br>file = open('example.txt', 'r')<br>content = file.read()<br>file.close()<br> |
flush() | 把缓冲区的数据立即写入文件,而不等待缓冲区满。在需要确保数据及时写入文件时使用。 | python<br>file = open('example.txt', 'w')<br>file.write('Hello')<br>file.flush() # 立即写入<br> |
read([size]) | 从文件中读取指定字节数的数据,如果未指定 size ,则读取整个文件内容。返回读取的字符串(文本模式)或字节对象(二进制模式)。 | python<br>file = open('example.txt', 'r')<br>content = file.read(10) # 读取前 10 个字符<br> |
readline() | 读取文件的一行内容,包括行末的换行符。每次调用会读取下一行,到文件末尾返回空字符串。 | python<br>file = open('example.txt', 'r')<br>line = file.readline()<br>print(line)<br> |
readlines() | 读取文件的所有行,并将每行作为一个元素存储在列表中返回。 | python<br>file = open('example.txt', 'r')<br>lines = file.readlines()<br>for line in lines:<br> print(line)<br> |
seek(offset[, whence]) | 移动文件指针到指定位置。offset 是偏移量,whence 是参考位置(0 表示文件开头,1 表示当前位置,2 表示文件末尾)。 | python<br>file = open('example.txt', 'r')<br>file.seek(5) # 移动到第 5 个字节处<br> |
tell() | 返回文件指针当前的位置,即从文件开头到当前位置的字节数。 | python<br>file = open('example.txt', 'r')<br>position = file.tell()<br>print(position)<br> |
truncate([size]) | 截断文件,使其长度为 size 字节。如果未指定 size ,则从当前文件指针位置开始截断。 | python<br>file = open('example.txt', 'r+')<br>file.truncate(10) # 截断为 10 字节<br> |
write(str) | 向文件中写入字符串(文本模式)或字节对象(二进制模式)。返回写入的字符数或字节数。 | python<br>file = open('example.txt', 'w')<br>num_chars = file.write('Hello')<br>print(num_chars)<br> |
writelines(lines) | 向文件中写入一个字符串列表,不会自动添加换行符。 | python<br>lines = ['Line 1', 'Line 2', 'Line 3']<br>file = open('example.txt', 'w')<br>file.writelines(lines)<br> |
__next__() | 用于迭代文件对象,每次返回文件的下一行,等同于 readline() 。通常在 for 循环中隐式调用。 | python<br>file = open('example.txt', 'r')<br>try:<br> while True:<br> line = next(file)<br> print(line)<br>except StopIteration:<br> pass<br> |
文本文件的操作
文本文件的读取
- 1.
read()
read()
方法会读取文件的全部内容,然后将其作为一个字符串返回。你可以选择性地传入一个参数,以此指定要读取的字节数。
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
- 2.
readline()
readline()
方法每次读取文件的一行内容,并将其作为一个字符串返回。每调用一次该方法,就会读取下一行。
file = open('example.txt', 'r')
line = file.readline()
print(line)
file.close()
- 3.
readlines()
readlines()
方法会读取文件的所有行,然后将它们作为一个字符串列表返回,列表中的每个元素代表文件的一行。
file = open('example.txt', 'r')
lines = file.readlines()
for line in lines:
print(line)
file.close()
文本文件的写入
wrIte
:write()
方法用于将一个字符串写入文件。它接受一个字符串作为参数,并将该字符串写入文件的当前位置。如果文件以追加模式('a'
)打开,数据将被添加到文件末尾;如果以写入模式('w'
)打开,文件会被清空然后写入新内容。
# 以写入模式打开文件
with open('test.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is a test.')
writelines
:writelines()
方法用于将一个字符串序列(如列表、元组等)写入文件。它会依次将序列中的每个字符串写入文件,但同样不会自动添加换行符。
二进制文件操作
文件的定位
tell()
:
tell()
方法的作用是返回文件当前的指针位置,也就是从文件开头到当前位置的字节数。
with open('example.txt', 'r') as file:
file.read(5)
position = file.tell()
print(f"当前文件指针位置: {position}")
seek()
方法用于移动文件指针到指定的位置。它接收两个参数:
offset:
表示要移动的字节数。
whence:
是一个可选参数,用于指定从哪个位置开始移动,有三个可选值:
0:
从文件开头开始计算(默认值)。
1:
从当前位置开始计算。
2:
从文件末尾开始计算。
with open('example.txt', 'r') as file:
file.read(5)
file.seek(3, 1)
content = file.read()
print(content)
文件处理
重命名
可以使用 os.rename()
函数来重命名文件。该函数接受两个参数,第一个参数是旧的文件名,第二个参数是新的文件名。
import os
old_name = 'old_file.txt'
new_name = 'new_file.txt'
try:
os.rename(old_name, new_name)
print(f"文件 {old_name} 已成功重命名为 {new_name}")
except FileNotFoundError:
print(f"错误: 文件 {old_name} 未找到。")
except FileExistsError:
print(f"错误: 文件 {new_name} 已存在。")
except Exception as e:
print(f"发生未知错误: {e}")
文件删除
使用 os.remove()
函数可以删除文件。该函数接受一个参数,即要删除的文件的路径。
import os
file_to_delete = 'file_to_delete.txt'
try:
os.remove(file_to_delete)
print(f"文件 {file_to_delete} 已成功删除。")
except FileNotFoundError:
print(f"错误: 文件 {file_to_delete} 未找到。")
except PermissionError:
print(f"错误: 没有权限删除文件 {file_to_delete}。")
except Exception as e:
print(f"发生未知错误: {e}")
目录操作
1. os.mkdir()
os.mkdir()
函数用于创建一个新的目录。它仅能创建单层目录,若父目录不存在或者目标目录已存在,就会抛出异常。
语法:
os.mkdir(path, mode=0o777, *, dir_fd=None)
path
:要创建的目录的路径。mode
:可选参数,用于指定新目录的权限,默认是0o777
。dir_fd
:可选参数,是一个文件描述符。
示例:
import os
# 要创建的目录路径
new_dir = 'new_directory'
try:
os.mkdir(new_dir)
print(f"成功创建目录: {new_dir}")
except FileExistsError:
print(f"目录 {new_dir} 已存在。")
except FileNotFoundError:
print(f"父目录不存在,无法创建 {new_dir}。")
2. os.chdir()
os.chdir()
函数用于改变当前的工作目录。也就是把当前程序操作的默认目录切换到指定的目录。
语法:
os.chdir(path)
path
:要切换到的目标目录的路径。
示例:
import os
# 要切换到的目录
new_path = 'new_directory'
try:
os.chdir(new_path)
print(f"已成功切换到目录: {new_path}")
except FileNotFoundError:
print(f"目录 {new_path} 不存在。")
3. os.getcwd()
os.getcwd()
函数用于获取当前的工作目录。它会返回一个字符串,表示当前程序操作的默认目录。
语法:
os.getcwd()
示例:
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前工作目录是: {current_dir}")
4. os.rmdir()
os.rmdir()
函数用于删除一个空目录。若目录不为空,就会抛出 OSError
异常。
语法:
os.rmdir(path)
path
:要删除的目录的路径。
示例:
import os
# 要删除的目录
dir_to_remove = 'new_directory'
try:
os.rmdir(dir_to_remove)
print(f"成功删除目录: {dir_to_remove}")
except FileNotFoundError:
print(f"目录 {dir_to_remove} 不存在。")
except OSError:
print(f"目录 {dir_to_remove} 不为空,无法删除。")