引言Python作为一种广泛使用的编程语言,提供了丰富的文件操作方法,使得文件处理变得高效便捷。本文将详细介绍20种Python文件操作方法,涵盖文件读取、写入、修改、删除等多个方面,帮助读者全面了解...
Python作为一种广泛使用的编程语言,提供了丰富的文件操作方法,使得文件处理变得高效便捷。本文将详细介绍20种Python文件操作方法,涵盖文件读取、写入、修改、删除等多个方面,帮助读者全面了解Python文件操作的魅力。
使用open()函数可以打开文件,返回一个文件对象。
with open('example.txt', 'r') as f: content = f.read()使用文件对象的read()、readline()、readlines()等方法可以读取文件内容。
with open('example.txt', 'r') as f: content = f.read() print(content)使用文件对象的write()、writelines()方法可以写入文件。
with open('example.txt', 'w') as f: f.write('Hello, World!')使用文件对象的seek()方法可以定位到文件特定位置,然后进行修改。
with open('example.txt', 'r+') as f: content = f.read() f.seek(0) content = content.replace('Hello', 'Hi') f.write(content)使用os.remove()函数可以删除文件。
import os
os.remove('example.txt')使用os.path.exists()函数可以检查文件是否存在。
import os
print(os.path.exists('example.txt'))使用os.path.getsize()函数可以获取文件大小。
import os
print(os.path.getsize('example.txt'))使用fileinput模块可以读取文件行数。
import fileinput
for line in fileinput.input('example.txt'): print(line)使用os.path模块可以处理文件路径。
import os
print(os.path.join('folder', 'file.txt'))使用os.rename()函数可以重命名文件。
import os
os.rename('example.txt', 'new_example.txt')使用os.makedirs()函数可以创建目录。
import os
os.makedirs('new_folder')使用os.rmdir()函数可以删除目录。
import os
os.rmdir('new_folder')使用os.walk()函数可以遍历目录。
import os
for root, dirs, files in os.walk('folder'): print(root, dirs, files)使用zipfile模块可以压缩文件。
import zipfile
with zipfile.ZipFile('example.zip', 'w') as zipf: zipf.write('example.txt')使用zipfile模块可以解压文件。
import zipfile
with zipfile.ZipFile('example.zip', 'r') as zipf: zipf.extractall('extracted_folder')使用cryptography模块可以加密文件。
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
with open('example.txt', 'rb') as f: original = f.read()
encrypted = cipher_suite.encrypt(original)
with open('example.txt', 'wb') as f: f.write(encrypted)使用cryptography模块可以解密文件。
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
with open('example.txt', 'rb') as f: encrypted = f.read()
decrypted = cipher_suite.decrypt(encrypted)
with open('example.txt', 'wb') as f: f.write(decrypted)使用hashlib模块可以计算文件校验和。
import hashlib
hash_obj = hashlib.sha256()
with open('example.txt', 'rb') as f: for chunk in iter(lambda: f.read(4096), b""): hash_obj.update(chunk)
print(hash_obj.hexdigest())使用shutil模块可以分割文件。
import shutil
shutil.copyfileobj(open('example.txt', 'rb'), open('example_part1.txt', 'wb'))
shutil.copyfileobj(open('example.txt', 'rb'), open('example_part2.txt', 'wb'))使用shutil模块可以合并文件。
import shutil
with open('example_part1.txt', 'rb') as f1, open('example_part2.txt', 'rb') as f2: shutil.copyfileobj(f1, open('example.txt', 'wb')) shutil.copyfileobj(f2, open('example.txt', 'ab'))Python提供了丰富的文件操作方法,可以帮助开发者高效便捷地处理文件。通过本文的介绍,相信读者已经对Python文件操作有了更深入的了解。在实际应用中,可以根据需求选择合适的文件操作方法,提高开发效率。