Learning Python3 in file读写operation, Table of Contentsmanagement and on under 文management器 using
fileoperation is programmingin非常 important 一部分, 它允许我们读取 and 写入data to filein, implementationdata 持久化store. in Pythonin, fileoperation非常 simple 直观, 主要through in 置 open()function来implementation.
Pythonin fileoperation主要including:
usingopen()function打开file, 语法such as under :
open(file, mode='r', encoding=None)
parameter说明:
file: filepathmode: 打开模式, 默认 for 'r' (只读) encoding: 编码方式, for 于文本file, 建议指定编码, such as'utf-8'常用 打开模式:
'r': 只读模式 (默认) 'w': 写入模式, 会覆盖原 has in 容'a': 追加模式, in file末尾添加 in 容'x': creation模式, creation new file, such as果file已存 in 则报错'r+': 读写模式'w+': 读写模式, 会覆盖原 has in 容'a+': 读写模式, in file末尾添加 in 容打开file after , 可以using以 under method读取file in 容:
read(): 读取整个filereadline(): 读取一行readlines(): 读取所 has 行, 返回list# 读取整个file
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
# 读取所 has 行 to list
with open('example.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
打开file after , 可以using以 under method写入file in 容:
write(): 写入stringwritelines(): 写入stringlist# 写入file
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!\n')
f.write('Welcome to Python file operations.\n')
# 写入 many 行
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('output.txt', 'a', encoding='utf-8') as f:
f.writelines(lines)
close(): 关闭fileflush(): 刷 new 缓冲区, 将 in 容写入filetell(): 返回当 before file指针位置seek(offset, whence): movefile指针位置
offset: 偏移量whence: 起始位置, 0表示file开头, 1表示当 before 位置, 2表示file末尾readable(): 判断file is 否 readable writable(): 判断file is 否可写closed: 判断file is 否已关闭# file指针operation
with open('example.txt', 'r+', encoding='utf-8') as f:
# 读取 before 10个字符
content = f.read(10)
print(f"First 10 characters: {content}")
# 获取当 before 位置
position = f.tell()
print(f"Current position: {position}")
# move to file开头
f.seek(0)
print(f"Position after seek(0): {f.tell()}")
# 读取一行
line = f.readline()
print(f"First line: {line.strip()}")
# move to file末尾
f.seek(0, 2)
print(f"Position at end: {f.tell()}")
# 写入 in 容
f.write('\nAdded at the end')
for 于二进制file (such asgraph片, 音频, 视频etc.) , 需要using二进制模式打开file, 即 in 模式string before 加 on 'b'.
# 读取二进制file
with open('image.jpg', 'rb') as f:
data = f.read()
print(f"File size: {len(data)} bytes")
# 写入二进制file
with open('copy_image.jpg', 'wb') as f:
f.write(data)
print("Binary file copied successfully")
Python os and os.pathmoduleproviding了file and Table of Contents operationfunctions.
os.getcwd(): 获取当 before 工作Table of Contentsos.chdir(path): 改变当 before 工作Table of Contentsos.listdir(path): 列出Table of Contentsin file and 子Table of Contentsos.mkdir(path): creation单级Table of Contentsos.makedirs(path): creation many 级Table of Contentsos.remove(path): deletefileos.rmdir(path): delete空Table of Contentsos.removedirs(path): delete many 级空Table of Contentsos.rename(src, dst): renamefile or Table of Contentsos.path.exists(path): 判断path is 否存 in os.path.isfile(path): 判断 is 否 for fileos.path.isdir(path): 判断 is 否 for Table of Contentsos.path.join(path1, path2, ...): 拼接pathos.path.abspath(path): 获取绝 for pathos.path.basename(path): 获取file名os.path.dirname(path): 获取Table of Contents名import os
import os.path
# 获取当 before 工作Table of Contents
print(f"Current working directory: {os.getcwd()}")
# 列出Table of Contents in 容
print("\nDirectory contents:")
for item in os.listdir('.'):
print(item)
# creationTable of Contents
if not os.path.exists('test_dir'):
os.mkdir('test_dir')
print("\nDirectory 'test_dir' created")
# creation many 级Table of Contents
if not os.path.exists('test_dir/sub_dir1/sub_dir2'):
os.makedirs('test_dir/sub_dir1/sub_dir2')
print("Multi-level directories created")
# checkpath
print("\nPath checks:")
print(f"'test_dir' exists: {os.path.exists('test_dir')}")
print(f"'test_dir' is directory: {os.path.isdir('test_dir')}")
print(f"'example.txt' is file: {os.path.isfile('example.txt')}")
# pathoperation
print("\nPath operations:")
full_path = os.path.join(os.getcwd(), 'test_dir', 'file.txt')
print(f"Full path: {full_path}")
print(f"File name: {os.path.basename(full_path)}")
print(f"Directory name: {os.path.dirname(full_path)}")
print(f"Absolute path: {os.path.abspath('test_dir')}")
# renamefile
try:
with open('old_name.txt', 'w') as f:
f.write('Test content')
os.rename('old_name.txt', 'new_name.txt')
print("\nFile renamed successfully")
except Exception as e:
print(f"Error: {e}")
# deletefile and Table of Contents
try:
if os.path.exists('new_name.txt'):
os.remove('new_name.txt')
print("File deleted successfully")
if os.path.exists('test_dir/sub_dir1/sub_dir2'):
os.removedirs('test_dir/sub_dir1/sub_dir2')
print("Directories deleted successfully")
except Exception as e:
print(f"Error: {e}")
on under 文management器 is Pythonin一种特殊 object, 它可以 in 进入 and 退出code块时执行specific operation. in fileoperationin, usingwith语句可以自动managementfile 打开 and 关闭, 即使 in operation过程in发生exception, 也能确保file被正确关闭.
# usingwith语句 (推荐)
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# file会自动关闭
# 不usingwith语句 (不推荐)
f = open('example.txt', 'r', encoding='utf-8')
try:
content = f.read()
print(content)
finally:
f.close() # 必须手动关闭file
usingwith语句 good 处:
creation一个filecopytool, support文本file and 二进制file copy, 并显示copy进度.
import os
def copy_file(src, dst, buffer_size=1024*1024):
"""
copyfile
Args:
src: sourcesfilepath
dst: 目标filepath
buffer_size: 缓冲区 big small , 默认1MB
Returns:
bool: copy is 否成功
"""
try:
# checksourcesfile is 否存 in
if not os.path.isfile(src):
print(f"Error: Source file '{src}' does not exist.")
return False
# 获取file big small
file_size = os.path.getsize(src)
print(f"Copying file: {src} -> {dst}")
print(f"File size: {file_size} bytes")
# 打open-sourcefile and 目标file
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
copied = 0
while True:
# 读取缓冲区 big small data
buffer = fsrc.read(buffer_size)
if not buffer:
break
# 写入data
fdst.write(buffer)
copied += len(buffer)
# 计算并显示进度
progress = (copied / file_size) * 100
print(f"Progress: {progress:.2f}% ({copied}/{file_size} bytes)", end='\r')
print("\nCopy completed successfully!")
return True
except Exception as e:
print(f"Error copying file: {e}")
return False
# testfilecopy
source_file = 'example.txt'
destination_file = 'example_copy.txt'
# 先creation一个testfile
with open(source_file, 'w', encoding='utf-8') as f:
for i in range(1000):
f.write(f"Line {i+1}: This is a test line for file copying.\n")
# copyfile
copy_file(source_file, destination_file)
# verificationcopy结果
print("\nVerifying copy:")
if os.path.exists(destination_file):
print(f"Destination file created: {destination_file}")
print(f"Source file size: {os.path.getsize(source_file)} bytes")
print(f"Destination file size: {os.path.getsize(destination_file)} bytes")
if os.path.getsize(source_file) == os.path.getsize(destination_file):
print("File sizes match - copy successful!")
else:
print("File sizes don't match - copy failed!")
else:
print("Destination file not created - copy failed!")
creation一个文本fileanalysis器, statisticsfilein 行数, 单词数 and 字符数.
def analyze_file(file_path):
"""
analysis文本file
Args:
file_path: filepath
Returns:
dict: package含行数, 单词数 and 字符数 dictionary
"""
# implementation你 code
pass
# testfunction
file_path = 'example.txt'
result = analyze_file(file_path)
print(f"File analysis for {file_path}:")
print(f"Lines: {result['lines']}")
print(f"Words: {result['words']}")
print(f"Characters: {result['characters']}")
creation一个Table of Contents遍历器, 递归遍历Table of Contentsin 所 has file, 并statistics不同class型file 数量.
import os
def traverse_directory(directory):
"""
遍历Table of Contents
Args:
directory: Table of Contentspath
Returns:
dict: package含fileclass型 and 数量 dictionary
"""
# implementation你 code
pass
# testfunction
dir_path = '.'
result = traverse_directory(dir_path)
print(f"Directory traversal for {dir_path}:")
for file_type, count in result.items():
print(f"{file_type}: {count}")
creation一个logfile生成器, 生成package含时间戳 and message logfile.
import datetime
def write_log(log_file, message, log_level='INFO'):
"""
写入log
Args:
log_file: logfilepath
message: logmessage
log_level: log级别, 默认 for 'INFO'
"""
# implementation你 code
pass
# testfunction
log_file = 'app.log'
write_log(log_file, 'Application started')
write_log(log_file, 'User logged in', 'INFO')
write_log(log_file, 'Database connection failed', 'ERROR')
write_log(log_file, 'Application closed', 'INFO')
# 读取并显示log
with open(log_file, 'r') as f:
print("Log contents:")
for line in f:
print(line.strip())