Python超详细基础文件操作(详解版)
    		       		warning:
    		            这篇文章距离上次修改已过443天,其中的内容可能已经有所变动。
    		        
        		                
                
# 打开文件
file = open('example.txt', 'r')  # 以只读方式打开文件
 
# 读取文件内容
content = file.read()  # 读取文件全部内容
print(content)
 
# 关闭文件
file.close()  # 关闭文件
 
# 打开文件并写入内容
file = open('example.txt', 'w')  # 以写入模式打开文件,如果文件存在则覆盖
file.write('Hello, World!')  # 写入内容
file.close()  # 关闭文件
 
# 读取文件的每一行
file = open('example.txt', 'r')
for line in file:
    print(line, end='')  # 打印每一行,end=''防止自动换行
file.close()
 
# 使用with语句自动管理文件资源
with open('example.txt', 'r') as file:
    for line in file:
        print(line, end='')
 
# 使用seek移动文件读取位置
file = open('example.txt', 'r')
file.seek(5)  # 将读取位置移动5个字节
print(file.read())  # 从当前位置开始读取
file.close()
 
# 文件和目录操作
import os
 
# 检查文件是否存在
if os.path.exists('example.txt'):
    print('文件存在')
 
# 获取文件大小
size = os.path.getsize('example.txt')
print(f'文件大小: {size} 字节')
 
# 创建目录
os.mkdir('new_directory')
 
# 列出目录内容
files = os.listdir('.')
print(files)
 
# 重命名文件
os.rename('example.txt', 'new_example.txt')
 
# 移动文件
os.replace('new_example.txt', 'example.txt')
 
# 删除文件
os.remove('example.txt')这段代码展示了如何在Python中进行基本的文件操作,包括打开、读取、写入、关闭文件,处理文件的每一行,以及使用with语句来自动管理文件资源,移动读取位置,检查文件是否存在,获取文件大小,创建目录,列出目录内容,重命名文件,移动文件,以及删除文件。
评论已关闭