Windows/Mac Python写入文件名时的非法字符处理(OSError: [Errno 22] Invalid argument:)
程序员文章站
2022-03-04 10:14:02
问题在把数据处理结果按名称存储为文件时,文件名中有特殊字符会出现错误。主要是Windows系统。解决方法:替换title中非法字符。比如用“_”:re.sub('[\/:*?"<>|]','_',title)。举例Windows文件名和代码(以英文引号“”为例):import csvif __name__ =='__main__' : csv_list = [[1],[2],[3],[4]] # 要写入的行 name = '"HPC" ARCHITECH'...
问题
在把数据处理结果按名称存储为文件时,文件名中有特殊字符会出现错误。
主要是Windows系统。
解决方法:
替换title中非法字符。比如用“_”:re.sub('[\/:*?"<>|]','_',title)
。
举例
Windows
文件名和代码(以英文引号“”为例):
import csv
if __name__ =='__main__' :
csv_list = [[1],[2],[3],[4]] # 要写入的行
name = '"HPC" ARCHITECH'
with open("/Users/apple/Downloads/%s.csv"%(name),"w",encoding="UTF-8",newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(csv_list)
上述文件名Windows系统下会报错:(中文引号不会报错,可以存储)
OSError: [Errno 22] Invalid argument: 'C:\\Users\\abc\\Desktop\\redo_code\\"HPC" ARCHITECH.csv'
改为:(这里使用”_“替换,也可以按照需要替换成其他)
if __name__ =='__main__' :
csv_list = [[1],[2],[3],[4]] # 要写入的行
name = '"HPC" ARCHITECH'
title = "%s.csv"%(name)
filename = re.sub('[\/:*?"<>|]','_',title) # 处理非法字符
with open("/Users/apple/Downloads/%s"%(filename),"w",encoding="UTF-8",newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(csv_list)
Mac
分别用一些含特殊字符的名称直接写入文件名进行测试。
import csv
if __name__ =='__main__' :
csv_list = [[1],[2],[3],[4]]
# 这些都可以正常写入
name = '"HPC" [ARCHITECH]'
name = '"HPC" <ARCHITECH>'
name = '"HPC" \ARCHITECH'
name = '"HPC" *ARCHITECH'
name = '"HPC" &ARCHITECH'
name = '"HPC" ?ARCHITECH'
name = '"HPC" :ARCHITECH'
name = '"HPC" ARCHITECH'
name = '“HPC” ARCHITECH'
# 这几个不能正常写入
name = '"HPC" /ARCHITECH'
name = '"HPC" :ARCHITECH'
with open("/Users/apple/Downloads/%s.csv"%(name),"w",encoding="UTF-8",newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(csv_list)
Mac下上面大部分字符不会报错,可以正常存储。
几个不能正常存储的:
1. 英文冒号
中文冒号”:“可以正常存储(如上图),英文冒号”:“会被改成/。(或许当有”/“存储需求时可以替换成英文冒号。)
2. 右斜杠“/”
“/”会被当成路径分隔符。报错没有此路径。
FileNotFoundError: [Errno 2] No such file or directory: '/Users/apple/Downloads/"HPC" /ARCHITECH.csv'
本文地址:https://blog.csdn.net/Parzival_/article/details/107282750