Python文件管理实现模拟社交媒体时出现Errno 2文件未找到错误
问题分析
从错误路径database/users//posts/2.lzs可以看出两个核心问题:
- 空用户ID存在:关注列表中包含空字符串,导致路径拼接时出现
//,触发文件不存在错误。这是因为从following.lzs读取内容并split(";")后,没有过滤空元素(比如文件末尾多了分号,或内容格式为user1;;user2)。 - 固定循环逻辑不合理:
getFeed函数中硬编码循环10次,既可能超出关注用户列表的长度,又强制假设每个用户都有10个帖子,而实际很多用户的帖子数量不足,直接触发FileNotFoundError。
解决方案
1. 清理关注列表的空元素
在处理关注列表时,过滤掉空字符串和空白字符,避免无效用户ID传入getFeed。
2. 重构getFeed函数逻辑
- 遍历每个关注用户,而非固定循环10次
- 检查用户帖子目录是否存在,避免无效路径
- 动态读取用户所有帖子(或按编号尝试读取前N个),并处理文件不存在的情况
- 使用
os.path.join构建路径,适配不同系统的路径分隔符
代码修改
修改关注列表处理代码
if option == "1": following = "" with open(f"{db_url}/users/{logged}/following.lzs", "r") as f: following = f.read().strip() if following: # 过滤空元素,确保所有用户ID有效 following = [user for user in following.split(";") if user.strip()] getFeed(following)
重构后的getFeed函数(动态读取所有帖子)
import os def getFeed(users=[]): global returnVal returnVal = [] for user_id in users: # 构建用户帖子目录路径 post_dir = os.path.join("database", "users", user_id, "posts") # 检查目录是否存在 if not os.path.isdir(post_dir): continue # 遍历目录下所有.lzs帖子文件 for filename in os.listdir(post_dir): if filename.endswith(".lzs"): post_path = os.path.join(post_dir, filename) try: with open(post_path, "r") as f: content = f.read().strip() if content: returnVal.append(content) except Exception as e: print(f"读取帖子失败: {e}")
可选:按编号读取前10个帖子(保留原逻辑但修复错误)
如果需要保留“读取每个用户前10个帖子”的逻辑,可修改为:
import os def getFeed(users=[]): global returnVal returnVal = [] for user_id in users: for post_num in range(1, 11): post_path = os.path.join("database", "users", user_id, "posts", f"{post_num}.lzs") # 检查文件是否存在 if not os.path.isfile(post_path): continue with open(post_path, "r") as f: content = f.read().strip() if content: returnVal.append(content)
内容的提问来源于stack exchange,提问作者LolzTheDeveloper
相关产品推荐
相关产品推荐

