1with open("file.txt") as file_in:
2 lines = []
3 for line in file_in:
4 lines.append(line)
1r for reading
2r+ opens for reading and writing (cannot truncate a file)
3w for writing
4w+ for writing and reading (can truncate a file)
5rb for reading a binary file. The file pointer is placed at the beginning of the file.
6rb+ reading or writing a binary file
7wb+ writing a binary file
8a+ opens for appending
9ab+ Opens a file for both appending and reading in binary. The file pointer is at the end of the file if the file exists. The file opens in the append mode.
10x open for exclusive creation, failing if the file already exists (Python 3)
1f = open('filename.txt', 'r') #open for reading (default)
2f = open('filename.txt', 'w') #open for writing, truncating the file first
3f = open('filename.txt', 'x') #open for exclusive creation, failing if the file already exists
4f = open('filename.txt', 'a') #open for writing, appending to the end of the file if it exists
5
1# Reference https://docs.python.org/3/library/functions.html#open
2
3# Method 1
4file = open("welcome.txt", "r") # mode can be r(read) w(write) and others
5data = file.read()
6file.close()
7
8# Method 2 - automatic close
9with open("welcome.txt") as infile:
10 data = file.read()
11
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()