Python如何获取文本文件每行的首字符?附现有代码与需求
提取文件每行首字符的实现方法
针对你的需求,这里提供两种实用的实现方式:
方式一:列表推导式快速处理
适合文件体积不大的场景,一次性读取所有行并处理:
with open('data.txt', 'r') as f: # 遍历每行,提取首字符并拼接换行符 output = [line[0] + '\n' for line in f.readlines()] print(output)
方式二:逐行读取(适合大文件)
避免一次性加载整个文件到内存,逐行处理更高效:
output = [] with open('data.txt', 'r') as f: for line in f: # 跳过空行,防止索引越界报错 if line.strip(): output.append(line[0] + '\n') print(output)
注意事项
- 使用
with语句可以自动关闭文件,比直接open()更安全规范。 - 如果文件中存在空行,建议加上空行判断(如方式二中的
if line.strip()),避免因line[0]触发索引错误。
内容的提问来源于stack exchange,提问作者Fearless problem solver
相关产品推荐
相关产品推荐

