学习Python编程7,文件

发布时间:2026/7/18 15:46:39

学习Python编程7,文件 打开读取文件file open(example.txt, r) data file.read() print(data)一行一行读取file open(example.txt, r) for line in file: print(line)错误异常处理try: file open(example.txt, r) except FileNotFoundError: print(File not found!)模式r读读取存在的文件。w写写入如果文件不存在则创建新文件存在则覆盖。a追加写入在文件尾追加写入如果文件不存在则创建新文件。b二进制。写入或读写二进制数据如图片或音频文件。写模式file open(example.txt, w) # Write to the file file.write(Hello, World!) # Close the file file.close()读模式file open(example.txt, r) # Read the file contents content file.read() # Print the contents print(content) # Close the file file.close()文件删除import os os.remove(example.txt)文件重命名import os os.rename(example.txt, new_example.txt)文件复制import shutil shutil.copy(example.txt, new_example.txt)文件移动import shutil shutil.move(example.txt, /path/to/new_folder/example.txt)读文件file open(example.txt, w) content file.read() line file.readline() file.close()写文件file open(example.txt, w) file.write(Hello, World!) lines [Line 1, Line 2, Line 3] file.writelines(lines) file.close()关闭文件file open(example.txt, w) # Perform operations on the file file.close()获取文件大小import os file_path example.txt try: file_size os.path.getsize(file_path) print(File size:, file_size, bytes) except FileNotFoundError: print(File not found.)import os file_path example.txt try: file_stats os.stat(file_path) file_size file_stats.st_size print(File size:, file_size, bytes) except FileNotFoundError: print(File not found.)扩展名import os filename example.txt extension os.path.splitext(filename)[1] print(File Extension:, extension)判断文件是否存在import os # Define the path of the file to check file_path /path/to/file # Check if the file exists if os.path.exists(file_path): print(File exists!) else: print(File does not exist.)import os # Define the path of the file to check file_path /path/to/file try: # Check if the file exists with open(file_path) as f: print(File exists!) except FileNotFoundError: print(File does not exist.)创建简单文件with open(example.txt, w) as file: print(Hello, World!, filefile)with open(example.txt, w) as file: file.write(Hello, World!)

相关新闻