You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环创建命名文件遇OSError及strip()用法咨询

Python 文件创建报错排查与 strip() 方法详解

错误原因

你遇到的OSError: [Errno 22] Invalid argument错误,根源是文件名包含非法的换行符\n。从报错路径Aang\n.txt能看出,循环里用来命名文件的name变量末尾带着换行符——这是因为最初用readlines()读取名称文件时,会保留每行末尾的换行符,直接把带换行符的字符串作为文件名,操作系统会判定为无效参数。

另外,最初代码还有个隐性问题:Python的字符串是不可变类型,final.replace("[name]", name)执行后不会修改原字符串,必须把返回值重新赋值给final,否则文件内容里的[name]根本不会被替换。

最初报错代码

with open("/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail+Merge+Project+Start/Mail Merge Project Start/Input/Names/invited_names.txt") as invited_names_file:
    names = invited_names_file.readlines()

with open("/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail+Merge+Project+Start/Mail Merge Project Start/Input/Letters/starting_letter.txt") as starting_letter_file:
    letter = starting_letter_file.read()

filename = "/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail+Merge+Project+Start/Mail Merge Project Start/Output/ReadyToSend/new.txt"

for name in names:
    with open(file=filename.replace("new", name), mode="w") as file:
        final = letter
        final.replace("[name]", name)
        file.write(final)

修正后的可用代码

with open("/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail+Merge+Project+Start/Mail Merge Project Start/Input/Names/invited_names.txt") as invited_names_file:
    names = invited_names_file.read().split('\n')

with open("/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail+Merge+Project+Start/Mail Merge Project Start/Input/Letters/starting_letter.txt") as starting_letter_file:
    letter = starting_letter_file.read().strip('\n')

filename = "/Users/XYZ/Desktop/technology/z 100 days of code z/python/Day 24 Mail+Merge+Project+Start/Mail Merge Project Start/Output/ReadyToSend/new.txt"

for name in names:
    with open(file=filename.replace("new", name), mode="w") as file:
        final = letter
        final = final.replace("[name]", name)
        file.write(final)
        print(final)

代码修正要点

  • 替换名称读取方式:用read().split('\n')替代readlines(),read()把整个文件读成一个字符串,再按换行符分割成列表,这样得到的name不再带末尾的换行符,避免了非法文件名问题。
  • 修复字符串替换逻辑:将final.replace("[name]", name)的返回值重新赋值给final,确保替换后的内容被正确写入文件。

strip() 方法详解

你在处理模板信件时用的strip('\n'),核心作用是移除字符串首尾指定的字符:

  • 如果调用strip()不带参数,默认会移除字符串首尾的所有空白字符(包括空格、换行符\n、制表符\t等)。
  • 当传入指定字符(比如这里的strip('\n')),则只会移除字符串开头和结尾出现的该字符,字符串中间的字符不会被改动。

在你的场景中,strip('\n')是为了清除模板信件首尾可能存在的多余换行符,保证生成的信件格式更整洁,不会出现开头或结尾的空行。


内容的提问来源于stack exchange,提问作者eddiek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 07:45:35