How do get Python to print the contents of a file [duplicate] - python

This question already has answers here:
How to print a file to stdout?
(11 answers)
Closed 9 years ago.
I'm trying to get Python to print the contents of a file:
log = open("/path/to/my/file.txt", "r")
print str(log)
Gives me the output:
<open file '/path/to/my/file.txt', mode 'r' at 0x7fd37f969390>
Instead of printing the file. The file just has one short string of text in it, and when I do the opposite (writing the user_input from my Python script to that same file) it works properly.
edit: I see what Python thinks I'm asking it, I'm just wondering what the command to print something from inside a file is.

It is better to handle this with "with" to close the descriptor automatically for you. This will work with both 2.7 and python 3.
with open('/path/to/my/file.txt', 'r') as f:
print(f.read())

open gives you an iterator that doesn't automatically load the whole file at once. It iterates by line so you can write a loop like so:
for line in log:
print(line)
If all you want to do is print the contents of the file to screen, you can use print(log.read())

open() will actually open a file object for you to read. If your intention is to read the complete contents of the file into the log variable then you should use read()
log = open("/path/to/my/file.txt", "r").read()
print log
That will print out the contents of the file.

file_o=open("/path/to/my/file.txt") //creates an object file_o to access the file
content=file_o.read() //file is read using the created object
print(content) //print-out the contents of file
file_o.close()

Related

Reading to a text file that does not have the text extension ".txt"

I am trying to read a file in Python 3.8 that is has the extension ".input". However, it is meant to be read as a text file. I tried to connect to the file using this code:
file = open('file.input', 'r')
print("The contents of the file are:",file)
However, it does not output the contents of "file.input" (I wrote "Hello World" in there as a sample message).
You need to call read (or one of the other read methods) on the object returned by open.
with open('file.input', 'r') as f:
print(f.read())
The with keyword is helpful for making sure the file you open gets closed. For more information on file I/O in python you should really read the documentation here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files.

open a file differences Python [duplicate]

This question already has answers here:
Understanding the Python 'with' statement
(5 answers)
Closed 4 years ago.
I am using python 2.x and I am going through company code, I found code that looks like:
filename = open('text.json', 'r')
# doSomething()
filename.close()
I am used to reading a file like so:
with open('text.json', 'r') as filename
# doSomething()
Can anyone explain what the difference is?
The second one is usually used with a context manager, so you can do
with open('text.json', 'r') as filename:
#your code
And you can access the file using the filename alias.
The benefit of that is that the context manager closes the file for you.
If you do manually as your first example you would need to manually call filename.close() after you used it to avoid file locking
When you open a file in python, you have to remember to close it when you're done.
So with your 1st line:
filename = open('text.json', 'r')
You'll need to remember to close the file.
The second version you have is typically used like this:
with open('text.json', 'r') as filename:
#block of code
This will automatically close the file after the block of code is run.
The other difference is the way you're naming the file object as "filename". You end up with the same object in both, just naming it in two different ways.

write function parameter inside file - Python [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 5 years ago.
I have a function which prints messages. then I want to save this messages into a file. But when I use .write(function parameter) it only write last message inside my file
writing_in_log = True
def print_and_log(message):
if write_in_log is True:
logFile = open("log", "w+")
logFile.write(message)
logFile.close()
I suppose you are not using the 'a' parameter when opening the file:
with open('file.txt', 'a') as file:
file.write('function parameter')
You probably open the file for each writing with open(yourfile, 'w') which will erase any content from the file before you write to it. If you want to append to your file, use open(yourfile, 'a').
In case this is not the error we need more information about what you are doing, i.e. the relevant parts of the code.

Replace line containing string with Python [duplicate]

This question already has answers here:
How to open a file for both reading and writing?
(4 answers)
Closed 6 years ago.
I'm trying to search through a file for a line that contain certain text and then replace that entire line with a new line.
I'm trying to use:
pattern = "Hello"
file = open('C:/rtemp/output.txt','w')
for line in file:
if pattern in line:
line = "Hi\n"
file.write(line)
I get an error saying:
io.UnsupportedOperation: not readable
I'm not sure what I'm doing wrong, please can someone assist.
You opened the file with 'w', meaning you are going to write to it. Then you try to read from it. So error.
Try reading from that file, and open another file for writing your output. If needed, when done, delete the first file and rename your output (temp) file to the first file's name.
You must be very new for python ^_^
You can write it like this:
pattern = "Hello"
file = open(r'C:\rtemp\output.txt','r') # open file handle for read
# use r'', you don't need to replace '\' with '/'
# open file handle for write, should give a different file name from previous one
result = open(r'C:\rtemp\output2.txt', 'w')
for line in file:
line = line.strip('\r\n') # it's always a good behave to strip what you read from files
if pattern in line:
line = "Hi" # if match, replace line
result.write(line + '\n') # write every line
file.close() # don't forget to close file handle
result.close()

Saving data into a text file

def ConvertFile():
FileNameIn = 'Hexdata.dat'
HexFile = open(FileNameIn, 'r')
for Line in HexFile:
print (Line)
print (Binary(Line))
HexFile.close()
So far I have that, which, when the program is run, converts the Hexidecimal number in the file to binary. This is in a file called Hexdata.dat
What I want to do is then save the binary output into a file called Binarydata.dat
How would I approach this in code? Be aware I'm new with Python and haven't covered this properly. I've tried different bits of code but they've all been unsuccessful, as really, they're all guesses.
I'm not asking you to solve the problem for me, but more asking how I would save the output of a program into a new text file.
You're already most of the way there. You already know how to open a file for reading:
HexFile = open(FileNameIn, 'r')
The 'r' there means "open for reading". If you look at the documentation for the open function, you will see that replacing the r with a w will open a file for writing:
OutputFile = open(FileNameOut, 'w')
And then you can send output to it like this:
print >>OutputFile, "Something to print"
Or use the write method on the file object:
OutputFile.write("Something to print\n")
Read the documentation of the open function (to open the file in write mode) and File Objects (to write information to the opened file).
You have to have 2 files in this script. The one you're reading from and the one you're writing to. Use the option wb (write binary) when opening the file you are going to write into. These two links should help a beginner with little or no Python knowledge complete your exercise: Intro to File Objects and Tutorial on File I/O.
You are currently opening the file in reading mode, so in order to write to the file, you would want to open the file with the buffering mode as ('w'). Quote from: http://docs.python.org. You can do so easily by replacing your 'r' with 'w'.
'w' for writing (truncating the file if it already exists
For more reference see open(name[, mode[, buffering]])
# the file name
FileNameIn = 'Hexdata.dat'
# create a file object: open it with "write" mode
HexFile = open(FileNameIn,"w")
for line in HexFile:
HexFile.write(Binary(line))
HexFile.close()
Have you tried using open('Binarydata.dat', 'w') for writing to the file? There are plenty of ways to write to a file, most of which can be found here: http://docs.python.org/tutorial/inputoutput.html

Categories