1 year ago

#378349

test-img

eezageeza

Unable to use file path from a .txt file after using .readlines()

I have a problem using a file path that has been read from a .txt file. I have created a .txt file that will hold various information to be used for different levels to a game I am creating.

If I create a .txt file from new and save it directly into my game root folder it will work but if I edit the .txt file (Keeping the information in the same order in the .txt file) I get a error:

FileNotFoundError: No such file or directory.

After the error I have to delete the .txt file and create a new one from scratch. I am wondering if there is something I am doing wrong or have I missed some Python magic that makes the file extension usable when it has been read from the the .txt file.

The code below is in my main.py file and is used to access the level data stored in the .txt file and place it in the level_data array. I know the Game_Data_Level_1.txt file is being opened, read and the data is being put into the array as I can print() the various bits of data held in the array.

pygame.init()
running = True
size = [Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)

level_data = []
my_file = open("Game_Data_Level_1.txt","r")  #opens data file
level_data = my_file.readlines()
my_file.close()

game = Game(screen, level_data) 
clock = pygame.time.Clock()

The level_data is then passed to the game class when it is created

class game():

    def __init__(self, screen, level_data):
        #Set up game initialisation code here
        self.surf = screen
        self.bg_img = pg.image.load(level_data[3]).convert()
        #self.bg_img = pg.image.load('graphics/space1.bmp').convert()
        self.bg_img = pg.transform.scale(self.bg_img, screen.get_size())

The line #self.bg_img = pg.image.load('graphics/space1.bmp').convert() is how I used to load the image but I want to create different levels with different backgrounds all read from files that hold all the separate level data.

I have searched for answers but haven't seen anyone having the same problem as this.

Can I use a filepath retrieved from a .txt file and use that to get the image i want?

Do I have to cast it to a str() before it can be used as a file extension? (I have tried this and it still doesn't work.)

I'm relatively new to Python so my coding is probably not up to standard so any suggestions that will be helpful is always greatly appreciated. If you need to see anymore code or anymore description then just ask.

python

filenotfounderror

0 Answers

Your Answer

Accepted video resources