简体   繁体   中英

python - selecting item from list

I am making something that just stores data line by line in a txt file, then it reads the file line by line. Stores each line in a list. then depending on what the user selects, its selects one of the item in the list

My problem is. for some reason when i add more than 1 line in the txt file. It seems to break the code. it will add an extra '\' and '\n' to the data/string.

example: data in the txt file

C:\desktop\test
D:\games\test

the program then displays these 2 from the file in a numbered list to the user

1 C:\desktop\test
2 D:\games\test

But when i(user) select 1 it says:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 
'D:\\games\\test\n'

it seems like it is adding extra \ and its adding the \n

does anyone have any idea why it would be doing this? here is my code

#read the file line by line and display in numbered list
with open('movielist.txt', 'r') as file:
    data = file.readlines()
    file.close()
    for i, item in enumerate(data, start=1):
        print('\n',i,item)

#user selects option 1
#goes to the chosen directory and selects random movie to play
user_choice = input('\nWhich directory do you want to select? ')      
if user_choice == '1':
    one = data[0]
    print('\nYou chose:',one)
    user = input('\nWould you like to get a random movie? ')
    if user == 'yes' or user == 'Yes':
        movie = random.choice([x for x in os.listdir(one) if os.path.isfile(os.path.join(one, x))])
        print("\nPlaying {}...".format(movie))
        webbrowser.open(os.path.join(one, movie))
    else:
        print('We can choose a movie later!')

Use file.read() instead of readlines() it will not consider new line whitespace("\n") on each line

with open('movielist.txt', 'r') as file:
    data = file.read()
    file.close()
    for i, item in enumerate(data, start=1):
        print('\n',i,item)

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