1with open('filename', 'a') as f: # able to append data to file
2 f.write(var1) # Were var1 is some variable you have set previously
3 f.write('data')
4 f.close() # You can add this but it is not mandatory
5
6with open('filename', 'r') as f: # able to read data from file ( also is the default mode when opening a file in python)
7
8with open('filename', 'x') as f: # Creates new file, if it already exists it will cause it to fail
9
10with open('filename', 't') as f: # opens the file in text mode (also is defualt)
11
12with open('filename', 'b') as f: # Use if your file will contain binary data
13
14with open('filename', 'w') as f: # Open file with ability to write, will also create the file if it does not exist (if it exists will cause it to fail)
15
16with open('filename', '+') as f: # Opens file with reading and writing
17
18# You can combine these as you like with the + for reading and writing
1#there are many modes you can open files in. r means read.
2file = open('C:\Users\yourname\files\file.txt','r')
3text = file.read()
4
5#you can write a string to it, too!
6file = open('C:\Users\yourname\files\file.txt','w')
7file.write('This is a typical string')
8
9#don't forget to close it afterwards!
10file.close()