0

Hi :) I need some help in adding headers and footer on a txt file in python. I have tried a few codes but none have worked. Hypothetically, if I need to add a header (lets say the title of the poem, "Beautiful life") to a file called poem.txt and need to add a footer at the bottom of the file (lets say the author of the poem, "- James") How can I do this? Also the output file should be a new txt format file.

*""" Your Beliefs, Your attitude, Your thoughts, Your perspective, How honest you are, Who your friends are, What books you read, How often you exercise, The type of food you eat, How many risks you take, How you interpret the situation, How kind you are to others, How kind you are to yourself,

How often you say “I love you.”, How often you say “thank you.”, How you express your feelings, Whether or not you ask for help, How often you practice gratitude, How many times you smile today, The amount of effort you put forth, How you spend / invest your money, How much time you spend worrying, How often you think about your past,

Whether or not you judge other people, Whether or not you try again after a setback, How much you appreciate the things you have """ *

I would appreciate any help. Thankyou so much :)

2 Answers2

2

Something like this should work, just change the variables at the top to suit:

header = "header"
footer = "footer"
input_file = "input.txt"
output_file = "output.txt"


with open(input_file, "r") as f:
    text = f.read()

text = header + "\n" + text + "\n" + footer

with open(output_file, "w") as f:
    f.write(text)
OtherBarry
  • 81
  • 1
  • 6
1

It's simple

HEADER = "your_header"
FOOTER = "your footer"
file1 = "your file location"
file2 = "your output file location"

f1 = open(file1 , "r")
txt = f1.read()
f1.close()
f2 = open(file2 , "w")
f2.write(HEADER + "\n" + txt + "\n" + FOOTER)
f2.close()
Pear
  • 351
  • 2
  • 12