Read and write files with ‘with’ statement in Python

I always keep forgetting how exactly with statement works with opening and reading the files in Python.

path = './path/filename.txt'

with open(path,'r') as file:
     data = file.readlines()
     print(data)

Or if you would like to avoid getting ‘\n’ after each line when using .readlines() you can use this instead:

data = file.read().splitlines()

Opening files with ‘with’ relieves the necessity of closing file thereafter:

# closing the file
file.close()

And the whole structure is cleaner and easier to use. As for the writing to file:

with open(path, 'w') as file:
   file.write('Hello!')
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x