| 5 | |
| 6 | |
| 7 | def main(): |
| 8 | # Open a file for writing and create it if it doesn't exist |
| 9 | f = open("textfile.txt","w+") |
| 10 | |
| 11 | # Open the file for appending text to the end |
| 12 | # f = open("textfile.txt","a+") |
| 13 | |
| 14 | # write some lines of data to the file |
| 15 | for i in range(10): |
| 16 | f.write("This is line %d\r\n" % (i+1)) |
| 17 | |
| 18 | # close the file when done |
| 19 | f.close() |
| 20 | |
| 21 | # Open the file back up and read the contents |
| 22 | f = open("textfile.txt","r") |
| 23 | if f.mode == 'r': # check to make sure that the file was opened |
| 24 | # use the read() function to read the entire file |
| 25 | # contents = f.read() |
| 26 | # print (contents) |
| 27 | |
| 28 | fl = f.readlines() # readlines reads the individual lines into a list |
| 29 | for x in fl: |
| 30 | print (x) |
| 31 | |
| 32 | if __name__ == "__main__": |
| 33 | main() |