A one-liner. No reason to do this.
with open('x.py') as f: s = f.read()
Answer from Mark Tolonen on Stack OverflowEasiest way to read/write a file's content in Python - Stack Overflow
2 ways to read files in python which one should you choose as best choice?
What is difference between read and read_file in configparser in Python 3? - Stack Overflow
python - How to read a file line-by-line into a list? - Stack Overflow
A one-liner. No reason to do this.
with open('x.py') as f: s = f.read()
Use pathlib.
Python 3.5 and above:
from pathlib import Path
contents = Path(file_path).read_text()
For lower versions of Python use pathlib2:
$ pip install pathlib2
Then
from pathlib2 import Path
contents = Path(file_path).read_text()
Writing is just as easy:
Path(file_path).write_text('my text')
Hi I started learning python, I thought there was only one way to read files. But I was wrong! After some days of coding and doing some mistakes, I noticed there are actually 2 ways to read files and choosing the right one can save me and you from some headaches.
In this post, I will show you those both methods with code example and try to explain you also.
Method 1:
# First method is Manual file handling
file = open('data.txt', 'r')
content = file.read()
print(content)
file.close() # I prefer you to use this!Explanation:
-
open()creates a file object. -
read()gets all the content from the file. -
close()releases the file from memory
I prefer you to use when you need more control in the file object.
Method 2:
# Second method using context manager
with open('data.txt', 'r') as file:
content = file.read()
print(content)
# File automatically closes hereexplanation:
-
with statement creates a context
-
file opens and gets assigned as the variable
-
file automatically closed when ends
Also, I prefer you when you want prevent memory leaks
Good bye, thanks for reading!
This code will read the entire file into memory and remove all whitespace characters (newlines and spaces) from the end of each line:
with open(filename) as file:
lines = [line.rstrip() for line in file]
If you're working with a large file, then you should instead read and process it line-by-line:
with open(filename) as file:
for line in file:
print(line.rstrip())
In Python 3.8 and up you can use a while loop with the walrus operator like so:
with open(filename) as file:
while line := file.readline():
print(line.rstrip())
Depending on what you plan to do with your file and how it was encoded, you may also want to manually set the access mode and character encoding:
with open(filename, 'r', encoding='UTF-8') as file:
while line := file.readline():
print(line.rstrip())
See Input and Ouput:
with open('filename') as f:
lines = f.readlines()
or with stripping the newline character:
with open('filename') as f:
lines = [line.rstrip('\n') for line in f]