学习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!", file=file)
with open("example.txt", "w") as file: file.write("Hello, World!")