# 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]
'''
相比open()函数会自动关闭文件
# File Objects
with open('test.txt', 'r') as f:
pass
print(f.closed)
'''
out:
True
'''
# 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]
'''
# 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]
'''
# 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]
'''