-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32 - fileOpen.py
More file actions
42 lines (33 loc) · 1.01 KB
/
32 - fileOpen.py
File metadata and controls
42 lines (33 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Open a file on the server
"""
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for
reading the content of the file
"""
f = open("demofile.txt", "r")
print(f.read())
# or
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
# Read only parts of the file
"""By default the read() method returns the whole text, but you can also specify
how many characters you want to return"""
f = open("demofile.txt", "r")
print(f.read(5))
# Read Lines
f = open("demofile.txt", "r")
print(f.readline())
# By calling readline() twice, you can read the first two lines
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
# Looping through the file to read the lines one by one
f = open("demofile.txt", "r")
for x in f:
print(x)
# Close files
f = open("demofile.txt", "r")
print(f.readline())
f.close()
"""You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file."""