logo
down
shadow

how to read a value from text HI file using python?


how to read a value from text HI file using python?

Content Index :

how to read a value from text HI file using python?
Tag : python , By : Alex
Date : November 24 2020, 03:01 PM

To fix the issue you can do You can just iterate over the .txt file lines and check if the line is valid, by checking if = is present in the line and then simply split() the line to get the key and value pair as:
kv_store = {}

with open("./file_path.txt", "r") as f:
    for line in f.readlines():
        # Strip any `\n` etc.
        line = line.strip()

        # Check if the line contains a key, value pair
        if len(line) > 0 and line.find("=") > 0:
            key, value = line.split("=", 1)
            kv_store[key] = value.strip('"')
print kv_store

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How do you read a text file, then split that text file into multiple text files with python?


Tag : python , By : hyperNURb
Date : March 29 2020, 07:55 AM
Hope that helps Use a to append the files each time use if/elif checks to see what each line startswith.
with open('original_file.txt', 'r') as infile,open("ABC1.txt","a") as ab1,open("ABC2.txt","a") as ab2,\
    open("ABC3.txt","a") as ab3,open("ABC4.txt","a") as ab4:
        for line in infile:
            if line.startswith("ABC1"):
                ab1.write(line)
            elif line.startswith("ABC2"):
                ab2.write(line)
            elif line.startswith("ABC3"):
                ab3.write(line)
            elif line.startswith("ABC4"):
                ab4.write(line) 
def insert_break(s,n, br):
    while s:
        yield "{}{}".format(s[:n],br)
        s = s[n:]
with open('output.txt', 'r') as f,open('updated.txt', 'a') as f1:
    inserted= "".join((insert_break(f.read(),181,"\n")))
    f1.write(inserted)

with open('updated.txt', 'r') as infile,open("ABC1.txt","a") as ab1,open("ABC2.txt","a") as ab2,\
        open("ABC3.txt","a") as ab3,open("ABC4.txt","a") as ab4:
            for line in infile:
                print line.startswith("ABC1"),line
                if line.startswith("ABC1"):
                    ab1.write(line)
                elif line.startswith("ABC2"):
                    ab2.write(line)
                elif line.startswith("ABC3"):
                    ab3.write(line)
                elif line.startswith("ABC4"):
                    ab4.write(line)

Python unable to read lines from text file after read()


Tag : python , By : billputer
Date : March 29 2020, 07:55 AM
this one helps. I have a problem whereby I am trying to first check a text file for the existence of a known string, and based on this, loop over the file and insert a different line. , You already know the answer:
#f_old.seek(0)  # <-- do we need to do this??
contents = f_old.read()
if '<dir>' in contents:
for line in contents.splitlines():
    # ....

Python : For loop to read a text file is not executing properly for all text file records


Tag : python , By : Olexiy P.
Date : March 29 2020, 07:55 AM
should help you out When reading a file, use the r mode.
Each line has a trailing \n, so you need to strip() them. Use repr(...) function so that you can see the trailing white spaces.
def search_for_job(job):
    with open('j.txt', 'r') as f:
        for line in f:
            if job in line:
                print(repr(job) + ' : Found in ' + repr(line))
                break


with open('n.txt', 'r') as job_names:
    for job in job_names:
        job = job.strip()
        print('Searching for job ' + repr(job))
        search_for_job(job)
job 1, name 2...
job 2, name 1...
job 3, nothing
name 1
name 2
name 3
$ python3 read.py
Searching for job 'name 1'
'name 1' : Found in 'job 2, name 1...\n'
Searching for job 'name 2'
'name 2' : Found in 'job 1, name 2...\n'
Searching for job 'name 3'

Read text file (containing list of Python filenames) and kill Python job if Python file appears in text file


Tag : python , By : littlefuzz
Date : March 29 2020, 07:55 AM
this will help you could try placing all the contents of the text file in a list, and iterate through that list to delete that particular file.
import os

file_list = [x.strip("\n") for x in open("file_containing_pys.txt","r")]

for file in file_list:
    os.system("sudo kill $(ps aux | grep 'python %s.py' | awk '{ print $2 }')"%file)

How to read a text from a specific world in a text tell the next space in the text file in python


Tag : python , By : shehan
Date : March 29 2020, 07:55 AM
should help you out If I'm reading you correctly, you want to keep all lines that:
Start with the word switch Follow after line beginning with switch but before the next empty line
keptlines = []
with open(myfile) as f:
    for line in f:
        if line.startswith('switch '):
            keptlines.append(line)
            for line in f:  # Continue iterating f for additional lines to keep
                if not line.rstrip():
                    break  # We hit an empty line, return to looking for switch
                keptlines.append(line)
            for line in f:  # Continue iterating f for additional lines to keep
                if not line.rstrip():
                    break  # We hit an empty line, return to looking for switch
                keptlines.append(line)
            keptlines.extend(takewhile(str.rstrip, f))
Related Posts Related QUESTIONS :
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • How to speed up calculating variance among sparse matrix
  • cupy code is not fast enough compared with numpy
  • How to count frequency of select values in Python pandas dataframe
  • Scrape Span Text from Google
  • Python watchdog, watch a directory and rename file on event.modification
  • Filtering rows in DataFrame with dependent conditions
  • How to check if a character is a not a part of number or URL in string?
  • Compare corresponding elements of a list
  • Python misinterprets 3 character string as UTF-8 continuation byte
  • Merge two columns in Pandas
  • Side Effect error in Python in an online compiler
  • How to convert a navigation list with depth levels to a parent-child flat list?
  • Retrieving values from a paired key dictionary in Python
  • How to test the current text of a Tkinter text box widget before inserting new text after user clicks on a button?
  • computing the Cumulative Sum, where Sum can be reset by a condition
  • Where do you specify your API key when making a request with the Google API python library?
  • Pandas DataFrame, computing the Time Difference between one row and other row which satisfies a condition
  • Discord.py bot not reading other bot's messages
  • How do I write a Django query that finds words in a Postgres column?
  • Download S3 File Using Boto3
  • Retrieve status of model training after closing notebook
  • If Current Date is in Column Then Show Row
  • How do I stay in a for loop's element until a condition is met?
  • QPainter point size is 1 pixel and can not be changed
  • How to download the excel file which has no link in Beautifulsoup?
  • Can't read the content of a certain page of a pdf file available online
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com