I've been trying to wrap my head around a method of parsing a text file and specifying the specific columns you want. So for example I ask them to input what columns they want to parse out of the text file.
Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17
So the person will input the txt file and then inputs that they want Column 0 and 2 it will give them a result of
Joe,19
Jake,19
Bob,19
I know I can do the .split()[0] but I dont want to hard code it I want it to work off the input. Im pretty sure its easy but for some reason I just cant get my head around the way to do it.
To make it a bit more in depth I want to make a program that you input a txt file and it asks you for what sections you would like then it prints out the seconds you wanted.
InputFileName = input("Please enter the name of file you would like to parse: ")
ParseSelection = input("Please enter the section's you want to parse: ")
and then from that it will open the txt file see that the user asked for Section 0 and 2 and just print them out as "Section 0 | Section 2"
Names.txt
Joe,Smith,19,15,17
Jake,Jones,19,15,17
Bob,Martin,19,15,17
open Names.txt it see that the person asked for Section 0 and 2 So it prints out
Joe | 19
Jake | 19
Bob | 19
CodePudding user response:
Your question is a bit vague, but i'll attempt to help you here. You're on the right lines, however for comma separated text it would be best to do this:
input().split(',')[0:4:2]
You can always use modules like this also (much easier):- https://docs.python.org/3/library/csv.html
CodePudding user response:
You could use the following:
columns = list('02')
where the input, '02', would indicate the user wants columns 0 and 2. Then you iterate over the file's lines and columns:
for lines in file:
for column in columns:
print(lines[int(column)], end=',')
print()
With your example, that'd return
Joe,19,
Jake,19,
Bob,19,
Also, if you're wondering how to read the input file, you may want to use the csv library.
