【发布时间】:2012-08-10 22:00:40
【问题描述】:
我正在为 python 中的串行端口创建嗅探器,但是在 Windows 中创建 CSV 文件时出现问题。我在某些时候拆分了我的程序,以避免 windows 和 linux 之间不兼容的可能性。它在 linux 上完美运行(测试 32 和 64 字节)。
def createNewFiles(self):
# Nons allons vérifier l'existance du dossier Sniffer_Serie_Result et le créer si besoin
# De même pour le fichier csv
if (os.name == "nt"): # pour windows
self.userPath = os.getenv('HOME') or os.getenv('USERPROFILE')
self.folderPath= os.path.abspath(self.userPath + "\\Sniffer_Serie_Result")
#exist_ok=True ==> cree le dossier si il n'existe pas
os.makedirs(self.folderPath,exist_ok=True)
self.timestampWithSec= self.timestampWithoutMilli() # utilisé dans les noms de fichier
self.filePathRequest= os.path.abspath(self.folderPath + "\\Request_at_" + self.timestampWithSec + ".csv")
self.filePathResponse= os.path.abspath(self.folderPath + "\\Response_at_" + self.timestampWithSec + ".csv")
self.filePathOverall = os.path.abspath(self.folderPath + "\\Overall_result_at_" + self.timestampWithSec + ".csv")
with open(self.filePathRequest, 'w') as f:
writer = csv.writer(f)
writer.writerow(["Kind of message","Timestamp","Message Hexa","Message ASCII"])
with open(self.filePathResponse, 'w') as f:
writer = csv.writer(f)
writer.writerow(["Kind of message","Timestamp","Message Hexa","Message ASCII"])
文件夹 Sniffer_Serie_Result 的创建没有错误 因此,此代码首先返回以下错误:
IOError: [Errno 22] 无效参数:'C:\Documents and Settings\stagiaire\Sniffer_Serie_Result\Request_at_......(实际日期和小时数).csv'
我尝试了很多字符串,比如原始字符串,但没有任何效果。
注意:我用于测试的 Windows 是 XP,这也需要在 7 上工作
我希望你能帮助我。 谢谢你的帮助!
我不能在星期四之前提供更多信息(目前家里没有互联网)
【问题讨论】:
-
首先,使用
os.path.join()连接目录而不是手动添加斜杠。其次,timestampWithSec包含什么? -
你好,我试试这个,时间戳包含str中的时间。
-
所以我尝试了您的解决方案,但错误完全相同
-
我的意思是:请粘贴
timestampWithSec的示例内容。我怀疑它只是包含一些对 Windows 无效的字符。 -
linux上的文件名示例(两个系统的名称相同):Request_at_2012-08-14_14:41:30.csv 所以时间戳包含准确:2012-08-14_14:41:30
标签: python windows file ioerror