Home > Net >  How to loop through file lines and add them a print list, iterating through
How to loop through file lines and add them a print list, iterating through

Time:02-02

I am trying to put a variable that is in a text file between two strings. For example, I have a text file like this:

123
456
789

I want to loop through each line and append it to two strings:

'The number,' 123 ' appears in the list'
'The number,' 456 ' appears in the list'
'The number,' 789 ' appears in the list'
a = str('This number')
b = str(' appears in the list')
file = open(r"My\File\Path\Example.txt", "r")
lines =len(file.readline())
for lines in file:
    print(a, print(file.readline(), b))

CodePudding user response:

It's almost fine, except for the last line of the provided code. Should be like this:

start_str = "The number,"
end_str = "appears in the list"

with open('example.txt', 'rt') as file:  # Open the text file in read-text mode
    for line in file.readlines():  # Iterate through each line of the text file
        print(start_str, line.strip(), end_str)  # Print formatted output. `.strip()` used to remove all leading and trailing whitespaces.

CodePudding user response:

with open('./Example.txt') as f:
  for l in f:
    print('The number', l.replace('\n',''), 'appears in the list')
  • Related