There is a file.txt in it information on different lines, tell me whether it is possible to obtain information from a specific line. I want the program to randomly output different lines from this textual
Closed due to the fact that off-topic participants MaxU , Xander , Enikeyschik , 0xdb , Air 6 Mar at 3:42 .
It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:
- " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- MaxU, Xander, Enikeyschik, 0xdb, Air
- oneHave you already read something about working with text files in Python? - MBo
- I read something .. - WestSide
|
2 answers
now try
import random bored = [] with open("file.txt", "r") as fin: www = fin.read() for string in www.split('\n'): bored.append(string) chance = random.choice(bored) print(chance) or so
import random print(random.choice(open('file.txt', 'r').read().splitlines())) - one
split('\n')bad idea - text files do not always have a line delimiter\n, maybe\r\n, so just dobored = fin.splitlines(), well, afterchance = random.choice(bored)or immediatelychance = random.choice(fin.splitlines())- gil9red pm - Mona and so do - Wertartem
- It is possible, but I would prefer to close the file on the spot (through
with) :) Fst,'r'can be omitted, since reading mode and so default :) - gil9red - super. all perfectly. I think WestSide will be pleased. Thank you for pointing the way :) - Wertartem
|
Read lines to list:
with open('file.txt') as fp: lines = fp.readlines() then use it
print(lines[i]) |