简体   繁体   中英

How to pick random cars in python from txt file

i've came across this problem that i've been trying to solve: i want to use a txt to randomly pick a car from a txt file but i always get it wrong and i hoped that you could help me here is what i have done so far in this specific part:

import random

if user_input == "1":

  with open("cars.txt", "r") as call_uber:

      for line in call_uber:

          array1 = line.split(" : ")

          print(array1)

the objective is to randomly pick the first name of one of the txt file lines but i just managed to split them

ps: i'm a newbie at this.

To randomly pick a line, just add random.choice function :

import random

if user_input == "1":

    with open("cars.txt", "r") as call_uber:

        line = random.choice(call_uber.readlines())

        array1 = line.split(" : ")

        print(array1)

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