Skip to content
Advertisement

Store the contents of text file in return variable and manipulate wherever required in python?

I have below function & I am trying to get/store the contents of text file in another temp file(removing unnecessary line) with appending special character. But I also want the same content which is in temp text file with different special character next time but I am not able to do that.Below function is creating a temp file.To get desired output I need to create file every time with same function again which is not good way.Is there anything we can do without creating a temp/extra file and store the contents in return variable and append the special character whatever we want multiple times

import os
import re

def mainfest():
    pathfile = "abc_12.txt"
    with open(pathfile, 'r') as firstfile, open('tmp.txt', 'r') as s:
         for line in firstfile:
             if line.strip().startswith("-") or line.startswith("<"):
                print"ignore")
             elif re.search('\S', line):
                name = str(os.path.basename(line))
                s.write("*" +fname) 


def contents():
    temppath = "temp.txt"
    with open(temp path, 'r') as f:
         lines = f.readlines()
         lines+= lines 
         return lines   


manifest()
value = contents()

file abc_12.txt

---ABC-123

nice/abc.py
xml/abc.py

<<NOP-123
bacnice.py
abc.py

---CDEF-345
jkl.oy
abc.py

I want the contents of abc_12.txt file I can get in return something like that

abc.py
abc.py
nice.py
abc.py
jkl.oy
abc.py

and manipulate them wherever I want similar to below output

Output 1:

* abc.py
* abc.py
* nice.py
* abc.py
* jkl.oy
* abc.py

Output 2:

@@abc.py
@@abc.py
@@nice.py
@@abc.py
@@jkl.oy
@@abc.py

Advertisement

Answer

Maybe first you should read file, search names and keep on list

def read_data():
    results = []
   
    with open("abc_12.txt") as infile:
         for line in infile:
             if line.strip().startswith(("-", "<")):  # `startswith`/`endswith` can use tuple 
                print("ignore:", line)
             elif re.search('\S', line):
                name = os.path.basename(line)
                results.append(name)

    return results

And later you can use this list to create temp file or other file

data = read_data()

with open('temp.txt', 'w') as outfile:
    for line in data:
        outfile.write(f'* {line}')
        #print(f'* {line}', end='')
        
with open('other.txt', 'w') as outfile:
    for line in data:
        outfile.write(f'@@{line}')
        #print(f'@@{line}', end='')

EDIT:

Minimal working code.

I used io.StringIO only to simulate file in memory – so everyone can simply copy and test it.

import os
import re
import io

text = r'''---ABC-123

nice/abc.py
xml/abc.py

<<NOP-123
bacnice.py
abc.py

---CDEF-345
jkl.oy
abc.py
'''

def read_data():
    results = []
   
    with io.StringIO(text) as infile:
    #with open("abc_12.txt") as infile:
        for line in infile:
            line = line.strip()
            if line:
                if line.startswith(("-", "<")):  # `startswith`/`endswith` can use tuple 
                    print("ignore:", line)
                else:
                    name = os.path.basename(line)
                    results.append(name)

    return results

data = read_data()

with open('temp.txt', 'w') as outfile:
    for line in data:
        outfile.write(f'* {line}n')
        print(f'* {line}')
        
with open('other.txt', 'w') as outfile:
    for line in data:
        outfile.write(f'@@{line}n')
        print(f'@@{line}')

EDIT:

If you don’t want to save in file then you still need for-loop to create string

data = read_data()

string_1 = ''
for line in data:
    string_1 += f'* {line}n'
        
string_2 = ''
for line in data:
    string_2 += f'@@{line}n'

or to create new list (and eventually string)

data = read_data()

list_1 = []
for line in data:
    list_1.append(f'* {line}')
        
list_2 = []
for line in data:
    list_2.append(f'@@{line}')

string_1 = "n".join(list_1)
string_2 = "n".join(list_2)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement