# 检查文件是否存在 if os.path.exists('file.txt'): print("File exists")
# 获取文件的修改时间 import time mod_time = os.path.getmtime('file.txt') print(f"Last modified: {time.ctime(mod_time)}")
实际应用示例
复制文件
1 2 3 4 5 6 7 8 9 10 11 12
defcopy_file(src, dst): withopen(src, 'rb') as fsrc: withopen(dst, 'wb') as fdst: whileTrue: chunk = fsrc.read(1024 * 1024) # 每次读取1MB ifnot chunk: break fdst.write(chunk) print(f"Copied {src} to {dst}")
# 使用函数 copy_file('source.txt', 'destination.txt')
统计文件中的单词数
1 2 3 4 5 6 7 8 9
defcount_words(filename): withopen(filename, 'r', encoding='utf-8') as f: content = f.read() words = content.split() returnlen(words)
# 使用函数 word_count = count_words('file.txt') print(f"Number of words: {word_count}")
读取CSV文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defread_csv(filename): withopen(filename, 'r', encoding='utf-8') as f: lines = f.readlines() headers = lines[0].strip().split(',') data = [] for line in lines[1:]: values = line.strip().split(',') row = dict(zip(headers, values)) data.append(row) return data
# 使用函数 csv_data = read_csv('data.csv') for row in csv_data: print(row)