-3

data.txt

I want to read this file using python.

4 Answers4

4
f = open('path/to/file.txt')
content = f.read()
f.close()
1

writing to file

file1 = open('data.txt', 'w')
file1.writelines("hello world")
file1.close()

reading a file

file1 = open('data.txt', 'r')
Lines = file1.readlines()

if you dont understand feel free to ask me a question.

0

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'
ljdyer
  • 1,946
  • 1
  • 3
  • 11
0

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.

Codeman
  • 477
  • 3
  • 13