Python Python3 java
 

Python File I/O

This chapter only covers all the basic I/O functions. For more functions, please refer to the Python standard documentation.

Print to screen

The simplest way to output is to use the print statement, which you can pass zero or more comma-separated expressions. This function converts the expression you pass into a string expression and writes the result to the standard output as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

print "Python is a great language, isn't it?" 

The following results will appear on your standard screen:

Python is a great Language, isn't it? 

Read keyboard input

Python provides two built-in functions to read a line of text from standard input. The default standard input is the keyboard. As follows:

  • raw_input
  • input

raw_input function

The raw_input([prompt]) function reads a line from standard input and returns a string (with the trailing newline removed):

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
 
Str = raw_input("Please enter:")
print "What you typed is: "< Span class="pun">, str

This will prompt you to enter an arbitrary string and then display the same string on the screen. When I type "Hello Python!", its output is as follows:

Please enter:Hello /span>Python! 
The content you entered is: Hello Python! 

input function

The input([prompt]) function is basically similar to the raw_input([prompt]) function, but input can take a Python expression as input and return the result of the operation.

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
 
Str = input("Please enter:")
print "What you typed is: "< Span class="pun">, str

This produces the following results corresponding to the input:

please enter:[x*5 for x in range(2,10,2)]
What you typed is: [10, 20, 30, 40]

Now you can read and write to standard input and output. Now, let's see how to read and write the actual data files.

Python provides the necessary functions and methods for basic file operations by default. You can do most of the file operations with the file object.

Open function

You must first open a file with Python's built-in open() function, create a file object, and the associated method can call it for reading and writing.

grammar:

file object = open(file_name [, access_mode][, buffering])

The details of each parameter are as follows:

  • file_name: The file_name variable is a string value that contains the name of the file you want to access.
  • access_mode:access_mode determines the mode in which the file is opened: read-only, write, append, etc. See the full list below for all possible values. This parameter is not mandatory and the default file access mode is read-only (r).
  • buffering: If the value of buffering is set to 0, there will be no registration. If the value of buffering is 1, the row is stored when the file is accessed. If the value of buffering is set to an integer greater than 1, it indicates that this is the buffer size of the registration area. If a negative value is taken, the buffer size of the registration area is the system default.

A complete list of open files in different modes:

ModeDescription
tText mode (default).
xWrite mode, create a new file, and report an error if the file already exists.
bbinary mode.
+Open a file for updating (readable and writable).
UUniversal Wrap Mode (not recommended).
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. Generally used for non-text files such as pictures.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. Generally used for non-text files such as pictures.
wOpen a file for writing only. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one.
wbOpen a file in binary format for writing only. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one. Generally used for non-text files such as pictures.
w+Open a file for reading and writing. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one.
wb+Opens a file in binary format for reading and writing. If the file already exists, open the file and start editing from the beginning, ie the original content will be deleted. If the file does not exist, create a new one. Generally used for non-text files such as pictures.
aOpen a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file for writing.
abOpens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file for writing.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. Append mode will be used when the file is opened. If the file does not exist, create a new file for reading and writing.
ab+Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

The following picture summarizes these patterns very well:

mode r r+ w w+ a a+
read + + + +
write + + + + +
Overlay creation + + + +
cover + +
The pointer is at the beginning + + + +
Pointer at the end + +

File object properties

After a file is opened, you have a file object and you can get various information about the file.

The following is a list of all the properties associated with the file object:

PropertiesDescription
file.closed returns true if the file has been closed, otherwise returns false.
file.mode Returns the access mode of the opened file.
file.name Returns the name of the file.
file.softspaceIf you use the print output, you must follow a space character and return false. Otherwise it returns true.

The following example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 
fo = open("foo.txt", "w")
print "file name: ", fo.name
print "Is it closed? : ", fo.closed
print "Access mode : ", fo.mode
print "Whether to force a space at the end : ", fo.softspace

The above example output results:

Filename: foo. txt
Whether it is closed : False
Access Mode : w
Do you want to force spaces at the end : 0

close() method

The close() method of the File object flushes any information in the buffer that has not yet been written, and closes the file, after which it can no longer be written.

When a reference to a file object is reassigned to another file, Python closes the previous file. It is a good practice to close the file with the close() method.

grammar:

fileObject.close()

example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# Open a file
Fo = open("foo.txt", "w")
print "Filename: ", fo.name
 
# Close open files
Fo.close()

The above example output results:

Filename: foo. txt

Read and write files:

The file object provides a set of methods that make our file access easier. Let's see how to use the read() and write() methods to read and write files.

Write() method

The write() method writes any string to an open file. It's important to note that Python strings can be binary data, not just text.

The write() method does not add a newline character ('\n') at the end of the string:

grammar:

fileObject.write(string)

Here, the parameters passed are the contents to be written to the opened file.

example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Open a file
fo = open("foo.txt", "w")
fo.write( "www.welookups.com!\nVery good site!\n")

# Close open file
fo.close()

The above method creates a foo.txt file, writes the received content to the file, and finally closes the file. If you open this file, you will see the following:

$ cat foo.txt
www.welookups.com!
Very good site!

Read() method

The read() method reads a string from an open file. It's important to note that Python strings can be binary data, not just text.

grammar:

fileObject.read([count])

Here, the parameter passed is the byte count to be read from the opened file. This method reads in from the beginning of the file. If no count is passed, it will try to read as much as possible, most likely until the end of the file.

example:

Here we use the foo.txt file created above.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Open a file
fo = open("foo.txt", "r ")
str = fo.read(10)
print "The string read is : ", str
# Close open file
fo.close()

The above example output results:

The string read is : www.welookups

File location:


File targeting

The tell() method tells you the current position in the file. In other words, the next read and write will occur after so many bytes at the beginning of the file.

The seek(offset [,from]) method changes the position of the current file. The Offset variable indicates the number of bytes to move. The From variable specifies the reference position at which to start moving bytes.

If from is set to 0, this means that the beginning of the file is used as the reference position for the move byte. If set to 1, the current position is used as the reference position. If it is set to 2, the end of the file will be used as the reference location.

example:

Just use the file foo.txt we created above.






welookups is optimized for learning.© welookups 2018 -
All Right Reserved and you agree to have read and accepted our term and condition