Search code examples
pythonwindowsfileioerror

IOError 22 in python Invalid on windows


I'm creating a sniffer for serial port in python, but I have a problem when i create a CSV file in windows. I split my program on some point to avoid the possibility of incompatibility between windows and linux. It's works perfectly on linux (test on 32 and 64 bytes).

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"])

The folder Sniffer_Serie_Result is create without error So this code return the following error at the first with:

IOError: [Errno 22] Invalid argument: 'C:\Documents and Settings\stagiaire\Sniffer_Serie_Result\Request_at_......(Actual date and hours).csv'

I try lot of string like raw string and nothing works.

NB: The windows i use for my test is XP, this need to work on 7 too

I hope you can help me. Tks for your help!

I can't give no more information before thursday (no internet at home for the moment)


Solution

  • You are trying to use : characters in filename, while that character is reserved in Windows for drive names (e.g. c:/).

    You have to either:

    1. Modify timestampWithoutMilli() to use another time separator (like -),
    2. Substitute all : in obtained time string with another character (using .replace()), for example.