Python file.read() function output? - python

I am trying to output a file's contents to terminal using the File.read() function in Python, but keep receiving the following output which doesn't match my ".txt" file contents.
Python Code
from sys import argv
script, input_file = argv
def print_all(f):
print f.read
current_file = open(input_file)
print "Print File contents:\n"
print_all(current_file)
current_file.close()
Output:
Print File contents:
<built-in method read of file object at 0x1004bd470>

If you want to call a function, you will need () after the name of the function (along with any required arguments)
Therefore, in your function print_all replace:
print f.read # this prints out the object reference
with:
print f.read() # this calls the function

You just need to change
print f.read
to say
print f.read()

You should do a read()
current_file = open(input_file)
print "Print File contents:\n"
print_all(current_file.read())

You need to actually call the function in your print_all definition:
def print_all(f):
print f.read()

You haven't called the read method, you've just got it from the file class. In order to call it you have to put the braces. f.read()

Related

Attempt to use the open() function failing

I'm trying to learn to manipulate files on python, but I can't get the open function to work. I have made a .txt file called foo that holds the content "hello world!" in my user directory (/home/yonatan) and typed this line into the shell:
open('/home/yonatan/foo.txt')
What i get in return is:
<_io.TextIOWrapper name='/home/yonatan/foo.txt' mode='r' encoding='UTF-8'>
I get what that means, but why don't I get the content?
open() returns a file object.
You then need to use read() to read the whole file
f = open('/home/yonatan/foo.txt', 'r')
contents = f.read()
Or you can use readline() to read just one line
line = f.readline()
and don't forget to close the file at the end
f.close()
An example iterating through the lines of the file (using with which ensures file.close() gets called on the end of it's lexical scope):
file_path = '/home/yonatan/foo.txt'
with open(file_path) as file:
for line in file:
print line
A great resource on I/O and file handling operations.
You haven't specified the mode you want to open it in.
Try:
f = open("home/yonatan/foo.txt", "r")
print(f.read())

Directing print output to a .txt file

Is there a way to save all of the print output to a txt file in python? Lets say I have the these two lines in my code and I want to save the print output to a file named output.txt.
print ("Hello stackoverflow!")
print ("I have a question.")
I want the output.txt file to to contain
Hello stackoverflow!
I have a question.
Give print a file keyword argument, where the value of the argument is a file stream. The best practice is to open the file with the open function using a with block, which will ensure that the file gets closed for you at the end of the block:
with open("output.txt", "a") as f:
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
From the Python documentation about print:
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.
And the documentation for open:
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
The "a" as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead at the beginning of the with block, use "w".
The with block is useful because, otherwise, you'd need to remember to close the file yourself like this:
f = open("output.txt", "a")
print("Hello stackoverflow!", file=f)
print("I have a question.", file=f)
f.close()
You can redirect stdout into a file "output.txt":
import sys
sys.stdout = open('output.txt','wt')
print ("Hello stackoverflow!")
print ("I have a question.")
Another method without having to update your Python code at all, would be to redirect via the console.
Basically, have your Python script print() as usual, then call the script from the command line and use command line redirection. Like this:
$ python ./myscript.py > output.txt
Your output.txt file will now contain all output from your Python script.
Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py)
Use the logging module
def init_logging():
rootLogger = logging.getLogger('my_logger')
LOG_DIR = os.getcwd() + '/' + 'logs'
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
rootLogger.addHandler(consoleHandler)
return rootLogger
Get the logger:
logger = init_logging()
And start logging/output(ing):
logger.debug('Hi! :)')
Another Variation can be... Be sure to close the file afterwards
import sys
file = open('output.txt', 'a')
sys.stdout = file
print("Hello stackoverflow!")
print("I have a question.")
file.close()
Suppose my input file is "input.txt" and output file is "output.txt".
Let's consider the input file has details to read:
5
1 2 3 4 5
Code:
import sys
sys.stdin = open("input", "r")
sys.stdout = open("output", "w")
print("Reading from input File : ")
n = int(input())
print("Value of n is :", n)
arr = list(map(int, input().split()))
print(arr)
So this will read from input file and output will be displayed in output file.
For more details please see https://www.geeksforgeeks.org/inputoutput-external-file-cc-java-python-competitive-programming/
Be sure to import sys module. print whatever you want to write and want to save. In the sys module, we have stdout, which takes the output and stores it. Then close the sys.stdout . This will save the output.
import sys
print("Hello stackoverflow!" \
"I have a question.")
sys.stdout = open("/home/scilab/Desktop/test.txt", "a")
sys.stdout.close()
One can directly append the returned output of a function to a file.
print(output statement, file=open("filename", "a"))

Problems with reading and writing a text file in Python

This answer was solved by doing print (file.read())
I have a project called 'PyDOS'. I recently discovered that you can read and write files in Python, I implemented this and the writing bit worked. But when trying the read part, it gives a syntax. The code that's messing up the reading part is:
print file.read
This is the code with the first error:
def textviewer():
print ("Text Viewer.")
file_name = input("Enter a text file to view: ")
file = open(file_name, "r")
print file.read #This returns 'Syntax Error' when pressing F5
input("Press enter to close")
def edit(): #However, the writing function works just fine.
os.system('cls' if os.name == 'nt' else 'clear')
print ("EDIT")
print ("-------------")
print ("Note: Naming this current document the same as a different document will replace the other document with this one.")
filename = input("Plese enter a file name.")
file = open(filename, "w")
print ("Now, Write 5 lines.")
line1 = input()
line2 = input()
line3 = input()
file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.close()
print ("File saved!")
time.sleep(3)
It returns syntax error, I tried file.read() but instead showed:
<built-in method read of _io.TextIOWrapper object at 0x10ada08>
<built-in method read of _io.TextIOWrapper object at 0x10ada08>
That's the string representation of a function. What you want isn't the function itself, but rather to call the function.
In other words, you want file.read() instead of file.read.
Also, in Python 3.x, print is a function, not a keyword, so you want print(file.read()), not print file.read().
Incidentally, file is the name of a built-in function (albeit a deprecated one), so you should use a different variable name.

Reading a file in python via read()

Consider this snippet
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
current_file = open(input_file)
print_all(current_file)
Ref. line 4: Why do I have to use "print" along with "f.read()". When I use just f.read() it doesnt print anything, why ?
f.read() reads the file from disk into memory. print prints to the console. You will find more info on input and output in the documentation

Python command isn't reading a .txt file

Trying to follow the guide here, but it's not working as expected. I'm sure I'm missing something.
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
file = open("C:/Test.txt", "r");
print file
file.read()
file.read()
file.read()
file.read()
file.read()
file.read()
Using the readline() method gives the same results.
file.readline()
The output I get is:
<open file 'C:/Test.txt', mode 'r' at 0x012A5A18>
Any suggestions on what might be wrong?
Nothing's wrong there. file is an object, which you are printing.
Try this:
file = open('C:/Test.txt', 'r')
for line in file.readlines(): print line,
print file invokes the file object's __repr__() function, which in this case is defined to return just what is printed. To print the file's contents, you must read() the contents into a variable (or pass it directly to print). Also, file is a built-in type in Python, and by using file as a variable name, you shadow the built-in, which is almost certainly not what you want. What you want is this:
infile = open('C:/test.txt', 'r')
print infile.read()
infile.close()
Or
infile = open('C:/test.txt', 'r')
file_contents = infile.read()
print file_contents
infile.close()
print file.read()
You have to read the file first!
file = open("C:/Test.txt", "r")
foo = file.read()
print(foo)
You can write also:
file = open("C:/Test.txt", "r").read()
print(file)

Categories

Resources