Python using open (w+) FileNotFoundError

后端 未结 1 1204
無奈伤痛
無奈伤痛 2020-12-10 12:56
  1. Creating function saveTxtIndividualTracks(track,folder,i).Based on python3.4.3 and windows 7:

    def saveTxtIndividualTracks(track,folder,i):
        f = o         
    
    
            
1条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 13:20

    You are getting the error because the directory - E:/phoneTracks/TA92903URN7ff/ does not exist.

    Example to show this error -

    In [57]: open('blah/abcd.txt','w+')
    ---------------------------------------------------------------------------
    FileNotFoundError                         Traceback (most recent call last)
     in ()
    ----> 1 open('blah/abcd.txt','w+')
    
    FileNotFoundError: [Errno 2] No such file or directory: 'blah/abcd.txt'
    

    Got error in my code, because the directory blah/ does not exist.

    If the directory - TA92903URN7ff/ is constant, try creating it and then running. If its not constant, you can checkout os.path.exists to check if the directory exists or not, and if it doesn't exist, create one using os.mkdir .

    Example -

    import os, os.path
    def saveTxtIndividualTracks(track,folder,i):
        if not os.path.exists(folder):
             os.mkdir(folder)
        elif not os.path.isdir(folder):
             return #you may want to throw some error or so.
        f = open(os.path.join(folder, str(i)+'.txt'),'w+')
            for line in track:
                l=str(line[0])+','+str(line[1])+','+str(line[2])+'\n'
            f.write(l)
        f.close()
    

    Also, you should consider using os.path.join to join paths, instead of using string concatenation. And also using with statement for openning files as - with open(os.path.join(folder, str(i)+'.txt'),'w+') as f: , that way the file will automatically get closed once the with block ends.

    0 讨论(0)
提交回复
热议问题