Python File opening syntax - python

In Python 2.7, what is the difference between the two statements:
f = open("file_name", "r")
f = open("file_name").read()
I know both are opening a file, but is first opening the file in read mode and the latter is opening the file and then reading it?

The first will return an open file object in read mode.
The second will return the contents of an open file object in read mode.

f = open("file_name", "r")
f = open("file_name").read()
The second is same as writing f = open("file_name", 'r').read().
As per python documentation the mode is an optional parameter to open(). If it is not specified, the file is open in read mode.
The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the
way in which the file will be used. mode can be 'r' when the file will
only be read, 'w' for only writing (an existing file with the same
name will be erased), and 'a' opens the file for appending; any data
written to the file is automatically added to the end. 'r+' opens the
file for both reading and writing. The mode argument is optional; 'r'
will be assumed if it’s omitted.

Related

python: I/O file.read() is returning an error [duplicate]

I have this code:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
But when I try it, I get an error message like:
File "...", line 18, in <module>
for line in file:
UnsupportedOperation: not readable
Why? How do I fix it?
You are opening the file as "w", which stands for writable.
Using "w" you won't be able to read the file. Use the following instead:
file = open("File.txt", "r")
Additionally, here are the other options:
"r" Opens a file for reading only.
"r+" Opens a file for both reading and writing.
"rb" Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w" Opens a file for writing only.
"a" Open for writing. The file is created if it does not exist.
"a+" Open for reading and writing. The file is created if it does not exist.
Use a+ to open a file for reading, writing and create it if it doesn't exist.
a+ Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing. -Python file modes
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")
Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.
more modes:
r. Opens a file for reading only.
rb. Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w. Opens a file for writing only.
you can find more modes in here
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
Sreetam Das's table is nice but needs a bit of an update according to w3schools and my own testing. Unsure if this due to the move to python 3.
"a" - Append - will append to the end of the file and will create a file if the specified file does not exist.
"w" - Write - will overwrite any existing content and will create a file if the specified file does not exist.
"x" - Create - will create a file, returns an error if the file exist.
I would have replied directly but I do not have the rep.
https://www.w3schools.com/python/python_file_write.asp

How can I print a txt file content with utf-8 characters in Python? [duplicate]

I have this code:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
But when I try it, I get an error message like:
File "...", line 18, in <module>
for line in file:
UnsupportedOperation: not readable
Why? How do I fix it?
You are opening the file as "w", which stands for writable.
Using "w" you won't be able to read the file. Use the following instead:
file = open("File.txt", "r")
Additionally, here are the other options:
"r" Opens a file for reading only.
"r+" Opens a file for both reading and writing.
"rb" Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w" Opens a file for writing only.
"a" Open for writing. The file is created if it does not exist.
"a+" Open for reading and writing. The file is created if it does not exist.
Use a+ to open a file for reading, writing and create it if it doesn't exist.
a+ Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing. -Python file modes
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")
Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.
more modes:
r. Opens a file for reading only.
rb. Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w. Opens a file for writing only.
you can find more modes in here
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
Sreetam Das's table is nice but needs a bit of an update according to w3schools and my own testing. Unsure if this due to the move to python 3.
"a" - Append - will append to the end of the file and will create a file if the specified file does not exist.
"w" - Write - will overwrite any existing content and will create a file if the specified file does not exist.
"x" - Create - will create a file, returns an error if the file exist.
I would have replied directly but I do not have the rep.
https://www.w3schools.com/python/python_file_write.asp

How to save the ouput of a python file using subprocess and append all those in a single file?

Have a python code that generates different output everytime i run that.
How to save the all ouput that has been generated when i run that python script on loop using suprocess
Code I am using is overwriting the file not appending.
f = open("blah.txt", "w")
subprocess.call(["python","loop.py"], stdout=f)
Open your file in append mode ('a')
f = open("blah.txt", "a")
Mode Description
--- ---
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)
open file in append mode instead of write mode
and if u want error also to be logged in the same file then.
f = open("blah.txt", "a")
subprocess.call(["python","loop.py"], stdout=f,stderr=f)

Why does my text file keep overwriting the data on it?

I'm trying to pull some data from Facebook pages for a product and dump it all into a text file, but I find that the file keeps overwriting itself with the data. I'm not sure if it's a pagination issue or if I have to make several files.
Here's my code:
#Modules
import requests
import facebook
import json
def some_action(post):
print posts['data']
print post['created_time']
#Token
access_token = 'INSERT ACCESS TOKEN'
user = 'walkers'
#Posts
graph = facebook.GraphAPI(access_token)
profile = graph.get_object(user)
posts = graph.get_connections(profile['id'], 'posts')
#Write
while True:
posts = requests.get(posts['paging']['next']).json()
#print posts
with open('test121.txt', 'w') as outfile:
json.dump(posts, outfile)
Any idea as to why this is happening?
w overwrites, open with a to append or open the file once outside the loop:
append:
while True:
posts = requests.get(posts['paging']['next']).json()
#print posts
with open('test121.txt', 'a') as outfile:
json.dump(posts, outfile)
Open once outside the loop:
with open('test121.txt', 'w') as outfile:
while True:
posts = requests.get(posts['paging']['next']).json()
#print posts
json.dump(posts, outfile)
It makes more sense to use the second option, if you are going to be running the code multiple times then you can open with a outside the loop also, if the file does not exist it will be created, if it does data will be appended
This is because you are using the file operator with w mode, you are overwriting the content. You can use the a append mode:
It can be done like this
Modification:
with open('test121.txt', 'w') as outfile:
while True:
posts = requests.get(posts['paging']['next']).json()
json.dump(posts, outfile)
w overwrites on the existing file
i.e)
File1.txt:
123
code:
with open("File1.txt","w") as oup1:
oup1.write("2")
File1.txt after python run:
2
Its value is overwritten
a appends to the existing file
i.e)
File1.txt:
123
code:
with open("File1.txt","a") as oup1:
oup1.write("2")
File1.txt after python run:
1232
The written content is appended to the end.
Opening and Closing Files
to use actual data files reading and writing to the standard input and output.
Python provides basic functions and methods necessary to manipulate files by default. You can do your most of the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details:
file_name: The file_name argument is a string value that contains the name of the file that you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).
buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
Here is a list of the different modes of opening a file −
Modes and Description
r= Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb= Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+= Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+= Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
w= Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb= Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+= Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+= Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a= Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab= Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+= Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+= Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
Reading and Writing Files
The file object provides a set of access methods to make our lives easie with the use of read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
# Open a file
fo = open("file.txt", "wb")
fo.write( "Python is a great language");
# Closeopend file
fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.
Python is a great language.
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.
Example
Let's take a file foo.txt, which we created above.
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is

Why does my file get overwritten?

When using this code in python:
f = open('ping.log', 'r+')
f.write("["+time.ctime()+"]"+"Status")
f.close()
My file always gets overwritten. And only has one line in it, like this:
[Fri Sep 02 16:30:56 2011]Status
Why is it getting overwritten?
It's failing because you are effectively recreating the file each time as you are overwriting the first N bytes every time. If you wrote less bytes you'd see the "old" information still there.
You need to open the file for "append"
'a' opens the file for appending
Source
r+ sets the initial file pointer to the beginning. Either seek to the end or use a mode.
Check this question. Open the file with the "a" mode:
f = open("ping.log","a")
...
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the
way in which the file will be used. mode can be 'r' when the file will
only be read, 'w' for only writing (an existing file with the same
name will be erased), and 'a' opens the file for appending; any data
written to the file is automatically added to the end. 'r+' opens the
file for both reading and writing. The mode argument is optional; 'r'
will be assumed if it’s omitted.
so use
f = open('ping.log', 'a')
f.write("["+time.ctime()+"]"+"Status")
f.close()

Categories

Resources