Home > Back-end >  How Can I read a string from a txt file line by line and run it with a function?
How Can I read a string from a txt file line by line and run it with a function?

Time:07-21

I have a txt file named a.txt. In this file a has a string per line. I want to append these strings line by line to the keyword = {} dict and run my double_letter function for each line of string. How can I do it?

my double_letter function:

keyword = {}

def double_letter():
    print("\nDouble Letter:\n")
    idx = random.randint(0, len(keyword) - 1)
    keyword = keyword[:idx]   keyword[idx]   keyword[idx:]
    print(keyword)

CodePudding user response:

You can open, read and print the contents of a txt file as follows:

f = open("a.txt", "r")
for line in f:
    print(line)

You can add in your function for each run through the for loop, i.e. calling it during each line of the text:

f = open("a.txt", "r")
for line in f:
    print(line)
    double_letter()

CodePudding user response:

IIUC

Code

import random

def double_letter(line):
    '''
        Repeats random letter in line
    '''
    if line:
        idx = random.randint(0, len(line) - 1)
        return line[:idx]   line[idx]   line[idx:]
    else:
        return line     # does nothing with blank lines
    
with open("a.txt", "r") as f:                # with preferred with open file
    keyword = {}                             # setup results dictionary
    for line in f:
        line = line.rstrip()                 # remove the '\n' at the end of each line
        keyword[line] = double_letter(line)  # add line with it's repeat to dictionary
        
print(keyword)    

File a.txt

Welcome
To
Stackoverflow

Output

{'Welcome': 'Welcomee', 'To': 'Too', 'Stackoverflow': 'Stackoverfloow'}
  • Related