file structure

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0b4ba312-700c-4e7f-9242-56a0542ec713/Untitled.png

open a file

way 1: open()

# File Objects

f = open('test.txt', 'r') 
# path: pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped.

print(f.name)

**f.close()**

'''
out:
test.txt
[Finished in 2.4s]
'''

available modes

way 2: context manager

相比open()函数会自动关闭文件

# File Objects

with open('test.txt', 'r') as f:
	pass

print(f.closed)
'''
out:
True
'''

different ways to read(based on the context manager)

Read the entire file

# File Objects

with open('test.txt', 'r') as f:
	f_contents = **f.read()**
	print(f_contents)
'''
out:
1) This is a test file!
2) With multiple lines of data...
3)Third line
4) Fourth line
5) Fifth line
6) Sixth line
7) Seventh line
8) Eighth line
9) Ninth line
10) Tenth line
[Finished in 47ms]
'''

read by lines

# File Objects

with open('test.txt', 'r') as f:
	f_contents = **f.readlines()**
	print(f_contents)
'''
out:
['1) This is a test file!\\n', '2) With multiple lines of data...\\n', '3)Third line\\n', '4) Fourth line\\n', '5) Fifth line\\n', '6) Sixth line\\n', '7) Seventh line\\n', '8) Eighth line\\n', '9) Ninth line\\n', '10) Tenth line']
[Finished in 45ms]
'''

read a line

# File Objects

with open('test.txt', 'r') as f:
	f_contents = f.readline() # default end with a new line
	print(f_contents)

	f_contents = f.readline()
	print(f_contents,end='') # end with ''
'''
out:
1) This is a test file!

2) With multiple lines of data...
[Finished in 46ms]
'''

use iteration to read lines