简体   繁体   中英

how to search a text file in python 3

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

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!

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