Python为文件名添加时间戳遇OSError: [Errno 22]错误求助
解决Windows下文件名含特殊字符导致的OSError问题
嘿,这个问题我太熟悉啦!你碰到的OSError: [Errno 22] Invalid argument,核心原因是Windows系统的文件名不允许包含冒号(:)、空格这类特殊字符,而你生成的时间戳里正好同时有这俩“禁忌字符”,系统自然识别不了这个非法文件名~
看你的错误信息里的文件名:all_ds_pagetitles.txt2020-03-19 16:49:21,这里的空格和冒号都是Windows文件名的禁区,必须替换掉才行。
解决方案
我给你调整两处关键地方,就能轻松解决:
- 修改时间戳的格式,把空格换成下划线,冒号换成横杠(或者直接去掉),生成合法的时间字符串;
- 优化文件名的拼接逻辑,把时间戳放在文件名主体和扩展名之间,让文件名结构更清晰,也能保证
.txt扩展名正常生效。
修改后的完整代码
import pandas as pd from datetime import datetime csv_file = pd.read_csv('C:/Users/anujp/Desktop/sort/Entity_Resolution_Project/data/csv_files/all_web_final_ds.csv', usecols=['page_title']) page_title_list = list(csv_file['page_title']) # 生成不含非法字符的时间戳:用下划线替换空格,横杠替换冒号 timestamp_string = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") # 拼接成规范的文件名:主体_时间戳.txt filename = f'C:/Users/anujp/Desktop/sort/Entity_Resolution_Project/data/text_files/all_ds_pagetitles_{timestamp_string}.txt' with open(filename, 'w', encoding='utf-8') as f: for item in page_title_list: f.write(f'{item}\n')
这样修改后,生成的文件名会是类似all_ds_pagetitles_2020-03-19_16-49-21.txt的格式,既符合Windows的命名规则,又能直观通过时间戳判断文件的新旧,还能正常以文本文件打开~
内容的提问来源于stack exchange,提问作者Raj Rajeshwari Prasad
相关产品推荐
相关产品推荐

