0

I am not very sure where I have gone wrong.

I am trying to print the contents from the page in files.

Here is the code

File>>> If you fell down yesterday, stand up today

text_file = open("files.txt", "r")
print(text_file)
idjaw
  • 25,487
  • 7
  • 64
  • 83
poisonishere
  • 43
  • 1
  • 7
  • 2
    Possible duplicate of [Reading entire file in Python](https://stackoverflow.com/questions/7409780/reading-entire-file-in-python) – idjaw Jul 05 '17 at 22:07
  • 3
    Do -> `print(text_file.read())` and read the link provided. It will explain everything. – idjaw Jul 05 '17 at 22:07
  • [7.2 Reading and Writing Files](https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files) from the Tutorial. – wwii Jul 05 '17 at 22:35

2 Answers2

1

Take a look at the file objects documentation. An example of iterating over the file includes:

for line in text_file:
    print(line)

Or use text_file.readlines() to receive a list of lines:

['If you fell down yesterday, stand up today']
jhwang
  • 43
  • 7
  • It keeps giving me this Traceback (most recent call last): File "main.py", line 1, in text_file = open("files.txt") FileNotFoundError: [Errno 2] No such file or directory: 'files.txt' exited with non-zero status – poisonishere Jul 05 '17 at 22:21
  • 1
    @poisonishere You're probably not in the same directory that 'files.txt' is located in. Open your terminal there or `import os` and use `os.chdir(path)` – jhwang Jul 05 '17 at 22:28
0

The way this works in Python is that it takes the file and stores it as just a file in that variable. Thus, you're trying to print a literal file, not the contents. There are a few ways to read things, assuming fvar as the file object for a text doc.

fulltext = fvar.read()

That will put the full text as a string.

oneline = fvar.readline()

Puts one line as the string oneline. Best used in loops. It will read the next line each time it runs - when it hits the end, it will return an empty string.

linelist = fvar.readlines()

This takes every line, as read with readline, and puts it into a list. Performs the same as a loop that reads each line with readline and appends each line to a list.

Hope that helps!

Sam Carpenter
  • 377
  • 3
  • 16