1

I have a scenario where I want to read file using python.

Data in file: ABC.txt

"A","B","C"
"E","F","A"
"S","H","DD","ADF"
"G","L","LI","LO","YAU"
"H","KK","AD"
"J","GH","KL"
"L","OP","AM"
"O","LA","WE"

My Code:

with open('ABC.txt',"r") as f:
    lines = f.readlines()
    parameter = {"empid": "3", "empcd": "56", "ide": [lines]}

What I am actually looking is read file line by line and should be passed as an argument to "ide": [line].

Assume it goes through first iteration, entire string -> "A","B","C" will be passed to "ide": ["A", "B", "C"].

parameter = {"empid": "3", "empcd": "56", "ide": ["A", "B", "C"]}

second iteration:

parameter = {"empid": "3", "empcd": "56", "ide": ["E", "F", "A"]}

third iteration:

parameter = {"empid": "3", "empcd": "56", "ide": ["S", "H", "DD", "ADF"]}

Loop will continue until all records are read from file.

In Unix I know how to read file but not good with python how to achieve this using python ?

My Unix code:

while read -r line 
do 
    var=`echo $line` 
    parameter = '{"empid": "3", "empcd": "56", "ide": [ $(( var )) ] }'
done < ABC.txt

3 Answers 3

2

You can use ast.literal_eval to convert lines to list. For example:

from ast import literal_eval

with open("ABC.txt", "r") as f_in:
    for line in f_in:
        print(
            {"empid": "3", "empcd": "56", "ide": literal_eval("[" + line + "]")}
        )

Prints:

{'empid': '3', 'empcd': '56', 'ide': ['A', 'B', 'C']}
{'empid': '3', 'empcd': '56', 'ide': ['E', 'F', 'A']}
{'empid': '3', 'empcd': '56', 'ide': ['S', 'H', 'DD', 'ADF']}
{'empid': '3', 'empcd': '56', 'ide': ['G', 'L', 'LI', 'LO', 'YAU']}
{'empid': '3', 'empcd': '56', 'ide': ['H', 'KK', 'AD']}
{'empid': '3', 'empcd': '56', 'ide': ['J', 'GH', 'KL']}
{'empid': '3', 'empcd': '56', 'ide': ['L', 'OP', 'AM']}
{'empid': '3', 'empcd': '56', 'ide': ['O', 'LA', 'WE']}
Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to print want to get into parameter line in place of "ide" : [ values]
@codeholic24 So instead of print() do parameter = {"empid": "3", "empcd": "56", "ide": literal_eval("[" + line + "]")}
2

You can use json:

import json

for line in open("ABC.txt"):
     parameter = { "empid":"3", "empcd":"56", "ide": json.loads(f"[{line}]") }
     print(parameter)

Comments

0

you can also use a lambda function

fun1 = lambda x:x.strip().replace('"','').split(",")
new_lines = [fun1(i) for i in lines]
print(new_lines)

Output:

[['A', 'B', 'C'], ['E', 'F', 'A'], ['S', 'H', 'DD', 'ADF'], ['G', 'L', 'LI', 'LO', 'YAU']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.