-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_operations.py
66 lines (47 loc) · 1.76 KB
/
file_operations.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'''
Hence, in Python, a file operation takes place in the following order:
- Open a file
- Read or write (perform operation)
- Close the file
'''
#In mode, we specify whether we want to read r, write w or append a to the file.#
file = open("test.txt") # open file in current directory
#file = open("C:/Python38/README.txt") # specifying full path
f = open("test.txt", encoding = 'utf-8')
# perform file operations
f.close()
try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()
'''
The best way to close a file is by using the with statement. This ensures that the file is closed when the block inside the with statement is exited.
We don't need to explicitly call the close() method. It is done internally.
'''
todos = {
'A':'hemanth',
'B':'Loh'
}
import json
with open("student.json", "w") as write_file:
json.dump(todos, write_file,indent= 4, sort_keys=True )
f = open("test.txt",'r',encoding = 'utf-8')
f.read(4) # read the first 4 data
f.seek(0) # bring file cursor to initial position
f.tell() # get the current file position
#We can read a file line-by-line using a for loop. This is both efficient and fast.
for line in f:
print(line, end = '')
f.fileno() #Returns an integer number (file descriptor) of the file.
import os
os.getcwd() #Get Current Directory
os.chdir('C:\\Python') #Changing Directory
os.listdir() #List Directories and Files
os.listdir('G:\\') #List sub Directories and Files
os.mkdir('test') #Making a New Directory
os.rename('test','new_one') #Renaming a Directory or a File
os.remove('old.txt') # Removing File
os.rmdir('new_one') # Removing empty Directory
import shutil
shutil.rmtree('test') # Removing Directory along with sub Files