This chapter covers all the basic I/O functions available in Python. For more functions, please refer to standard Python documentation.
Printing to the Screen
The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −
Live DemoThis produces the following result on your standard screen −
Reading Keyboard Input
Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are −
- raw_input
- input
The raw_input Function
The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).
This prompts you to enter any string and it would display same string on the screen. When I typed 'Hello Python!', its output is like this −
The input Function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.
Gta sa 60 fps mod. PROXYEnableProxyLibrary=0InitProxyFunctions=1ProxyLibrary=GLOBALUseEffect=0AlternativeDepth=1AllowAntialias=1BugFixMode=0SkipShaderOptimization=0EFFECTEnableBloom=1EnableOcclusion=0EnableReflection=0EnableMotionBlur=0EnableWater=1EnableShadow=1DepthBias=0INPUTKeyUseEffect=123KeyBloom=120KeyOcclusion=121KeyReflection=100KeyCombination=16KeyShadow=119these are the best setting i choseif you have reflection on it flickers real bad and occulusion makes the game dark and blurry.
This would produce the following result against the entered input −
Opening and Closing Files
Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do 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
Python Write To File Append If Exists
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 −
Sr.No. | Modes & Description |
---|---|
1 | r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. |
2 | 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. |
3 | r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. |
4 | rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. |
5 | 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. |
6 | 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. |
7 | 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. |
8 | 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. |
9 | 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. |
10 | 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. |
11 | 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. |
12 | 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. |
The file Object Attributes
Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all attributes related to file object −
Sr.No. | Attribute & Description |
---|---|
1 | file.closed Returns true if file is closed, false otherwise. |
2 | file.mode Returns access mode with which file was opened. |
3 | file.name Returns name of the file. |
4 | file.softspace Returns false if space explicitly required with print, true otherwise. |
Example
Live DemoThis produces the following result −
The close() Method
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.
Syntax
Example
Live DemoThis produces the following result −
Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how to use 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
Here, passed parameter is the content to be written into the opened file.
Example
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.
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
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.
This produces the following result −
File Positions
The tell() method tells you the current position within the file; in other words, the next read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position.
Example
Let us take a file foo.txt, which we created above.
This produces the following result −
Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
The rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
Example
Following is the example to rename an existing file test1.txt −
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.
Syntax
Example
Following is the example to delete an existing file test2.txt −
Directories in Python
All files are contained within various directories, and Python has no problem handling these too. The os module has several methods that help you create, remove, and change directories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method which contains the name of the directory to be created.
Syntax
Example
Following is the example to create a directory test in the current directory −
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory. Arijit singh favourite songs download.
Syntax
Example
Following is the example to go into '/home/newdir' directory −
The getcwd() Method
The getcwd() method displays the current working directory.
Syntax
Example
Following is the example to give current directory −
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.
Syntax
Example
Following is the example to remove '/tmp/test' directory. It is required to give fully qualified name of the directory, otherwise it would search for that directory in the current directory.
File & Directory Related Methods
There are three important sources, which provide a wide range of utility methods to handle and manipulate files & directories on Windows and Unix operating systems. They are as follows −
- File Object Methods: The file object provides functions to manipulate files.
- OS Object Methods: This provides methods to process files as well as directories.
I'm used to doing
print >>f, 'hi there'
However, it seems that
print >>
is getting deprecated. What is the recommended way to do the line above?Update:Regarding all those answers with
martineau'n'
..is this universal or Unix-specific? IE, should I be doing 'rn'
on Windows?73.5k1010 gold badges101101 silver badges191191 bronze badges
Yaroslav BulatovYaroslav Bulatov37.7k1515 gold badges100100 silver badges159159 bronze badges
12 Answers
This should be as simple as:
Create Text File Python
From The Documentation:
Do not use
os.linesep
as a line terminator when writing files opened in text mode (the default); use a single 'n' instead, on all platforms.Some useful reading:
open()
- 'a' is for append, or use
- 'w' to write with truncation
os
(particularlyos.linesep
)
3,70822 gold badges2626 silver badges3030 bronze badges
JohnsywebJohnsyweb103k1818 gold badges148148 silver badges214214 bronze badges
You should use the
print()
function which is available since Python 2.6+For Python 3 you don't need the
import
, since the print()
function is the default.The alternative would be to use:
Quoting from Python documentation regarding newlines:
On output, if newline is None, any
Martin Tournoij'n'
characters written are translated to the system default line separator, os.linesep
. If newline is '
, no translation takes place. If newline is any of the other legal values, any 'n'
characters written are translated to the given string.19k1212 gold badges6565 silver badges101101 bronze badges
sorinsorin79.7k119119 gold badges385385 silver badges602602 bronze badges
The python docs recommend this way:
So this is the way I usually do it :)
Statement from docs.python.org:
It is good practice to use the 'with' keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.
j7nn7kj7nn7k10.5k1515 gold badges7070 silver badges8383 bronze badges
Regarding os.linesep:
Here is an exact unedited Python 2.7.1 interpreter session on Windows:
On Windows:
As expected, os.linesep does NOT produce the same outcome as
'n'
. There is no way that it could produce the same outcome. 'hi there' + os.linesep
is equivalent to 'hi therern'
, which is NOT equivalent to 'hi theren'
.It's this simple: use
n
which will be translated automatically to os.linesep. And it's been that simple ever since the first port of Python to Windows.There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows.
DO NOT USE os.linesep!
John MachinJohn Machin66.7k77 gold badges102102 silver badges163163 bronze badges
I do not think there is a 'correct' way.
I would use:
In memoriam Tim Toady.
HyperboreusHyperboreus22.5k77 gold badges3737 silver badges7373 bronze badges
In Python 3 it is a function, but in Python 2 you can add this to the top of the source file:
Then you do
KeithKeith32.3k88 gold badges4343 silver badges6262 bronze badges
If you are writing a lot of data and speed is a concern you should probably go with
f.write(..)
. I did a quick speed comparison and it was considerably faster than print(.., file=f)
when performing a large number of writes.On average
write
finished in 2.45s on my machine, whereas print
took about 4 times as long (9.76s). That being said, in most real-world scenarios this will not be an issue.If you choose to go with
print(.., file=f)
you will probably find that you'll want to suppress the newline from time to time, or replace it with something else. This can be done by setting the optional end
parameter, e.g.;Whichever way you choose I'd suggest using
with
since it makes the code much easier to read.Update: This difference in performance is explained by the fact that
write
is highly buffered and returns before any writes to disk actually take place (see this answer), whereas print
(probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.The performance difference now becomes much less pronounced, with an average time of 2.20s for
write
and 3.10s for print
. If you need to concatenate a bunch of strings to get this loooong line performance will suffer, so use-cases where print
would be more efficient are a bit rare.Robin KeskisarkkaRobin Keskisarkka
Since 3.5 you can also use the pathlib for that purpose:
Path.write_text(data, encoding=None, errors=None)
Open the file pointed to in text mode, write data to it, and close the file:
Jacques Kvam1,43211 gold badge1414 silver badges2424 bronze badges
johnsonjohnson88022 gold badges1111 silver badges1414 bronze badges
When you said Line it means some serialized characters which are ended to 'n' characters. Line should be last at some point so we should consider 'n' at the end of each line. Here is solution:
in append mode after each write the cursor move to new line, if you want to use 'w' mode you should add 'n' characters at the end of write() function:
Reza TanzifiReza Tanzifi
kmario23kmario2322.1k55 gold badges7272 silver badges8484 bronze badges
You can also try
filewriter
pip install filewriter
Writes into
my_file.txt
Takes an iterable or an object with
Emin Buğra SaralEmin Buğra Saral__str__
support. 2,56411 gold badge1313 silver badges2020 bronze badges
When I need to write new lines a lot, I define a lambda that uses a
print
function:This approach has the benefit that it can utilize all the features that are available with the
print
function.Update: As is mentioned by Georgy in the comment section, it is possible to improve this idea further with the
partial
function: IMHO, this is a more functional and less cryptic approach.
MxNxMxNx
protected by Community♦Dec 26 '16 at 18:26
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?