-1

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))
Woodford
  • 3,746
  • 1
  • 15
  • 29

2 Answers2

1

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.
maximilionus
  • 66
  • 1
  • 4
0
with open('./Example.txt') as f:
  for l in f:
    print('The number', l.replace('\n',''), 'appears in the list')
Jacob Kearney
  • 391
  • 11