I have this text file that has lists in it. How would I search for that individual list? I have tried using loops to find it, but every time it gives me an error since I don't know what to search for. I tried using a if statement to find it but it returns -1. thanks for the help
-
2Please give a [mcve], don't just vaguely describe the problem. – jonrsharpe Jan 12 '19 at 16:57
-
ok I will keep that in mind – chess_lover_6 Nov 19 '20 at 01:42
1 Answers
I was doing research on this last night. You can use pandas for this. See here: Load data from txt with pandas. One of the answers talks about list in text files.
You can use:
data = pd.read_csv('output_list.txt', sep=" ", header=None)
data.columns = ["Name", "b", "c", "etc."]
Add sep=" " in your code, leaving a blank space between the quotes. So pandas can detect spaces between values and sort in columns. Data columns isenter code here for naming your columns.
With a JSON or XML format, text files become more searchable. In my research I’ve decided to go with an XML approach. Here is the link to a blog that explains how do use Python with XML: http://www.austintaylor.io/lxml/python/pandas/xml/dataframe/2016/07/08/convert-xml-to-pandas-dataframe.
If you want to search the data frame try:
import pandas as pd
txt_file = 'C:\path\to\your\txtfile.txt'
df = pd.read_table(txt_file, sep = ",")
row = df.loc[df['Name'] == 'bob']
Print(row)
Now depending how your text file is formated, your results will not work for every text file. The idea of a dataframe in pandas helps u create a CSV file formats. This giving the process a repeatable structure to enable testing results. Again I recommend using a JSON or XML format before implementing pandas data frames in ur solution. U can then create a consistent result, that is testable too!

- 773
- 1
- 8
- 24
-
1This is not an acceptable answer, see https://meta.stackexchange.com/q/225370/248731 – jonrsharpe Jan 12 '19 at 17:06
-
Rusty Powers, but that doesn't say how to search for a string such as Bob. – chess_lover_6 Jan 12 '19 at 17:07