-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.py
79 lines (61 loc) · 1.65 KB
/
files.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
67
68
69
70
71
72
73
74
75
76
77
78
79
import os
# r = Read
# a = Append
# w = Write
# x = Create
# Read - Error if file does not exist
# we can mention rt to read and text file or rb to read binary file
f = open("names.txt", "r")
#
#print(f.read())
# to read first 4 characters of the file
# print(f.read(4))
# to read line by line manually
#print(f.readline())
#print(f.readline())
# read file line by line with loop
for line in f:
print(line)
# we should close this file
f.close()
# Read operation with try and except block
try:
f = open("names_list.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found")
finally:
f.close()
# Approach 1 Write - Write into file if exist else throw an error [ overwrite existing file ]
f = open("context.txt","w")
print("I deleted all the content of the file")
f.write("Hello from python")
f.close()
f = open("context.txt", "r")
print(f.read())
f.close()
# Approach 2 Write - Create file if not exist [ overwrite existing file ]
# Opens a file for writing, creates the file if it does not exist
f = open("name_list.txt", "w")
f.close()
# Avoid an error if it doesn't exist
if os.path.exists("newFile.txt"):
os.remove("newFile.txt")
else:
print("The file does not exist")
# Append - Update file if not exist
f = open("names.txt", "a")
f.write("\nAbhi")
f.close()
f = open("names.txt", "r")
print(f.read())
f.close()
# Create - Error if file exist
# Create the specified file, but returns an error if the file exists
# if not os.path.exists("newFile.txt"):
# f = open("newFile.txt", "x")
# f.close()
with open("morename.txt") as f:
content = f.read()
with open("names.txt", "w")as f:
f.write(content)