data.txt
I want to read this file using python.
file1 = open('data.txt', 'w')
file1.writelines("hello world")
file1.close()
file1 = open('data.txt', 'r')
Lines = file1.readlines()
if you dont understand feel free to ask me a question.
The with decorator below will automatically close the file when it's done.
with open("data.txt", encoding='utf-8') as file:
my_data = file.read()
If using runtime, be sure to include the four spaces before the second line, and press Enter another time to end the with statement before typing my_data to confirm the variable contains the text from the file.
Your session will look like this:
>>> with open("data.txt", encoding='utf-8') as file:
... my_data = file.read()
...
>>> my_data
'This is the text in the file'
Use with open() as
, as given below
_file = 'temp.txt'
with open(_file, 'r') as fyl:
ct = fyl.read()
#do something
This has the added benefit that the file is closed even is an exception occurs, so it's good practice to use with open() as
.