-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_handling.py
More file actions
59 lines (49 loc) · 1.68 KB
/
file_handling.py
File metadata and controls
59 lines (49 loc) · 1.68 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# python has several functions for making CRUD operations on files
# 'r'(default)- opens file for reading, 'a'- opens file for appending, 'w'- opens file for writing, 'x'- creates a specified file
# the above operations return errors if file doesnot exist except for 'w'
# in addition you can specify if the file should be handled as binary-'b' 0r text-'t'(default)
# f = open('demofile.txt') # same as f = open('demofile.txt', 'rt') file does not exist
# read file
f = open('demofile2.txt')
print(f.read())
print('--------\n')
# open on different location
women = open(r"C:\Users\hassan\Desktop\notepad\women.txt", "r")
print(women.read())
women.close() #close file
print('--------\n')
# read some parts of file
f = open('demofile2.txt')
print(f.read(15))
print('--------\n')
# read lines
print(f.readline())
print('\n----------------\n')
# write to an existing file
# "a" will append to the end of the file WHILE "w" overwrites existing file
f = open('demofile2.txt','a')
f.write('The forth line is added!')
f.close()
# open and read file after appending
f = open('demofile2.txt','r')
print(f.read())
print('\n----------------\n')
# overwrite file
f3 = open('demofile3.txt','w')
f3.write('Former content kaput! new content is ...')
f3.close()
# open and read file after overwriting
f3 = open('demofile3.txt','r')
print(f3.read())
print('\n----------------\n')
# Create a new file
f4 = open('newtxtfile.txt','x') # 'a' amd 'w'\can also be used if file doesn't exist
# delete a file
import os
# os.remove("newtxtfile.txt2")
# check if file exists before deleting
if os.path.exists('newtxtfile.txt'):
os.remove('newtxtfile.txt')
else:
print('File DNE')
# os.rmdir('empty_folder') deletes folder