Thursday, October 02, 2014

Python - How to Append A Line To The Beginning of A File

In Python, there is no way of appending a line to the beginning of a file with any built-in functions, here is a simple script shows you how to do it.

#!/usr/bin/python
import sys

# CSS style definition for wikitable
string = """This is the line I
want to add to the beginning of the file"""

file = "./a.txt"
def main():

    # Read all the content into string
    f = open(file, 'r')
    content = f.read()
    f.close()

    # Open each file for writing:
    f = open(file, 'w')
    f.seek(0)
    f.write(style_string)
    f.write(content)
    f.close()

if __name__ == "__main__":
    main()

No comments: