0

The following code searches for words given in the list and when matched writes the line to a csv row by row.

I am trying to find a solution so that instead of writing by row only, the 1st item in the list is column1 and 2nd item to column2 and so on.

parm_list = ["electricalAntennaTilt ","iuantSectorId ", "eUtranCellFDDId "]
os.remove("Parm.csv")
#keyword = input("Enter keyword here: ")
with open('Parm.csv', 'w', newline='\n', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["eNB", "Parameter", "Value"])

for filename in os.listdir(directory):
    for i in parm_list:
        if filename.endswith(".txt"):
            with open(filename, "r", encoding="UTF-8") as file:
                for line in file:
                    if re.search(i, line):
                        with open('Parm.csv', 'a', newline='\n', encoding='utf-8') as csvfile:
                            writer = csv.writer(csvfile)
                            writer.writerow([filename] + [line])


    else:
        continue

Current Output:

315655.txt electricalAntennaTilt                30

315655.txt iuantSectorId                        315655_1_4

Expected output:

315655.txt electricalAntennaTilt                30 iuantSectorId                        315655_1_4

3 Answers 3

1

I don't see your txt files, so just a guess:

import csv
import os
import re

directory = "~/Desktop" # put here a path to your directory

parm_list = ["electricalAntennaTilt ","iuantSectorId ", "eUtranCellFDDId "]
os.remove("Parm.csv")
#keyword = input("Enter keyword here: ")
with open("Parm.csv", "w", newline="\n", encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["eNB", "Parameter", "Value"])

for filename in os.listdir(directory):
    if filename.endswith(".txt"):
        row = [filename] # <--------- make a row for every file
        for i in parm_list:
            with open(filename, "r", encoding="UTF-8") as file:
                for line in file:
                    if re.search(i, line):
                        row.append(line) # < ----- fill the row

         # write the row to the csv file
         with open("Parm.csv", "a", newline="\n", encoding="utf-8") as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(row)
Sign up to request clarification or add additional context in comments.

Comments

1

Why do you close the file every time? Beside of that, try iterating over parameters (parm_list) in an inner loop instead:

parm_list = ["electricalAntennaTilt ","iuantSectorId ", "eUtranCellFDDId "]
os.remove("Parm.csv")
#keyword = input("Enter keyword here: ")
with open('Parm.csv', 'w', newline='\n', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=["eNB"] + parm_list) 
    writer.writeheader()

    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            with open(filename, "r", encoding="UTF-8") as file:
                data = {'eNB': filename}
                for line in file:
                    if data.keys() > set(parm_list):
                        break
                    for pattern in parm_list:
                        if pattern not in data and re.search(pattern, line):
                            data[pattern] = line.strip()

                writer.writerow(data)                         

2 Comments

Thanks madbird. Your code works, except it results in the first instance of the word in the file only, instead of all of them.
It's not clear for me, how you are going to handle the situation when there's a number of keywords attributed to a metric 1, and none of them for metric2. So I'm not sure how can I help you with that.
1

Not sure if this is what you are looking for, but change

with open('Parm.csv', 'a', newline='\n', encoding='utf-8') as csvfile:

to

with open('Parm.csv', 'a', newline='', encoding='utf-8') as csvfile:

in the second loop.

1 Comment

Thanks arun chand, unfortunately that doesnt get me the output i am looking for.

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.