简体   繁体   中英

FileNotFoundError: No such file or directory. Even though it exists

My code is currently very basic, as this is the start of my project. I run into this error which makes no sence. Here is the code:

import pygame 
import sys

def playsound():
 pygame.mixer.init()
 popsound = pygame.mixer.Sound('C:\School\Computing\flap.wav')
 popsound.play()

print(playsound())

For some reason, this error shows:

Traceback (most recent call last):
  File "C:/School/Computing/NEA_Project.py", line 9, in <module>
    print(playsound())
  File "C:/School/Computing/NEA_Project.py", line 6, in playsound
    popsound = pygame.mixer.Sound('C:\School\Computing\flap.wav')
FileNotFoundError: No such file or directory.

However, if I pick a different file from the same directory, it works no problem. Anyone got a fix for this?

Change your \ to \\ :

import pygame 
import sys

def playsound():
 pygame.mixer.init()
 popsound = pygame.mixer.Sound('C:\\School\\Computing\\flap.wav')
 popsound.play()

print(playsound())

The reason you should do this is because, in Python strings, backslashes are special characters , called escape characters. They are used in representing whitespace characters like tabs ( "\t" ), newlines ( "\n" ), and carriage returns ( "\r" ).

Prefixing a special character with "\" turns it into an ordinary character.


You can avoid the trouble altogether by simply using forward slashes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM