-1

How do I read a file by opening that particular file instead of printing it on the console? I've used the following code but it prints the contents of the file on the console.

fw=open("x.txt",'r+')
#fw.write("Hello\n")
#fw.write("Python is crazy af")
n=fw.read()
print(n)
fw.close()
  • 1
    `print(n)` prints the contents of `n`, which is the contents of the file after `n=fw.read()`. It is literally doing what you told it. If you don't want to print it... don't print it? "How do I read a file by opening that particular file" - you _did_ open that particular file, _and_ you _did_ read it. I don't understand what you are asking. – Amadan Jan 21 '19 at 00:24

2 Answers2

0

The builtin open function makes the contents of a file available, meaning you can manipulate it with your code. If you don't want to print a line of it, you can do .readlines(). If you don't want to print it you can do anything else you want with it like store it in a variable.

One last note about file context:

with open("filename.txt", "r") as file:
     for line in file:
         # Do something with line here

This pattern is guaranteed to close, instead of calling open and close separately.


But if you wanted to open a text editor...

https://stackoverflow.com/a/6178200/10553976

Charles Landau
  • 4,187
  • 1
  • 8
  • 24
0

How do I read a file by opening that particular file

The first 2 (non comment) lines of your answer do this:

fw=open("x.txt",'r+')
n=fw.read()

You have now read the contents of x.txt into the variable n

instead of printing it on the console?

Don't print it then. Remove the line

print(n)

and the contents of the file won't be printed.

Kim
  • 409
  • 3
  • 9