-
Notifications
You must be signed in to change notification settings - Fork 4
/
reading_file_examples.py
80 lines (66 loc) · 2.12 KB
/
reading_file_examples.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
80
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 16:57:00 2021
@author: mjach
"""
'''files character meaning in python'''
'''
'r' - open for reading its is default
'w' - open for writing, but delete the first one
'x' - open for new one creation, but fail it the file already exits
'a' - open for writing and adding more contents at the end if the file exits
'b' - open the file in binary mode
't' - open the file in text mode
'+' - open a file from disk for updating either reading or writing
'''
## always make sure file is closed
## the below examples are base on the current working directory
'''
#1. reading a jason file from same directory
'''
# my_file = open('sample1.json', 'r')
# fruit = my_file.read()
# print(fruit) # read and print entire file contents
# my_file.close()
'''
#2. reading a text file example from same directory
'''
# my_file = open('reading_my_file.txt', 'r')
# print(my_file.read())
# my_file.close()
'''
#3. reading a text file example from same directory
# with this its work like a try...catch ...finally
# it will close the file automatically
'''
# with open('reading_my_file.txt', 'r' ) as my_file:
# #fruit = my_file.read()
# print(my_file.read())
'''
#4. reading a text file example from same directory
'''
file = open('reading_my_file.txt')
#print(file.readline())# read only one line
#print(file.readline(2))# read only specific character from a line
#print(file.readlines())# reading all the lines and return as a list
#file.close()
'''
#5. reading a text file example from same directory
#iterting or going through each line of the text file with a while loop
'''
# with open('reading_my_file.txt', 'r') as my_file:
# line = my_file.readline()
# while line != '': # '' means empty string
# print(line, end='')
# line = my_file.readline()
'''
#6. reading a text file example iterating through for loop
# recommend option
'''
# with open('reading_my_file.txt','r') as my_file:
# for line in my_file.readlines():
# print(line, end='')
'''more simplified options'''
with open('reading_my_file.txt','r') as my_file:
for line in my_file:
print(line, end='')