Example of file read/write in python

Source: Internet
Author: User
Tags readline in python


The print keyword is used to output the following content to the screen.

Str = "I love Python"
>>> Print str
I love Python
>>> Sum = lambda arg1, arg2: arg1 + arg2
>>> Print '1 + 2 = % d' % sum (1, 2)
1 + 2 = 3
Input (), raw_input ()

Both functions read strings from the command line. The former parses and returns the read strings according to the Python syntax, and the latter processes the strings as strings.

>>> Raw_input ("CMD :")
CMD: 1 + 2
'1 + 2'
>>> Input ("CMD :")
CMD: 1 + 2
3
Open ()

File object = open (file_name [, access_mode] [, buffering])
# File_name: a string value
# Access_mode: read, write, append, etc.
# R reading only
# Rb reading only in binary format.
# R + reading and writing.
# Rb + reading and writing in binary format.
# W writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
# Wb writing only in binary format ....
# W + writing and reading ....
# Wb + writing and reading in binary format ....
# A Oappending ....
# AB appending in binary format ....
# A + Oappending and reading ....
# AB + appending and reading in binary format ....
# Buffering:
#0, no buffering takes place.
#1, line buffering is saved Med while accessing a file.
# An integer greater than 1, then buffering action is completed Med with the indicated buffer size.
# Negative, the buffer size is the system default (default behavior ).
FileObject attributes

Fo. closed

Returns true if file is closed, false otherwise.

Fo. mode

Returns access mode with which file was opened.

Fo. name

Returns name of the file.

Fo. softspace

Returns false if space explicitly required with print, true otherwise.

FileObject methods

Fo. close ()

Write unwritten data to a file and close the file object

Fo. write ()

Write a string to a file object

Fo. tell ()

Returns the position of file

Fo. seek (offset, [, from])

Move file location pointer

0 indicates starting from the file

1 indicates from the current position

2 indicates starting from the end of the file

OS module

OS. rename (cur_file_name, new_file_name)

Rename the file # OS. remove (file_name)

Delete an object

OS. mkdir ("newdir ")

Create a new folder

OS. chdir ("objdir ")

Switch working directory

OS. getcwd ()

Display current working directory

OS. rmdir ()

Delete folder

Write mode and append mode

If the file opened in Write and append modes does not exist, the file is created by default and its content is blank.

(1) r mode: write to a file

$ Cat file_0000py
Filename = "temp.txt"
F = open (filename, "w ")
F. write ("hello, world. \ n ")
F. write ("hi, python! \ N ")
F. close ()
$ Python file_1_py
$ Cat temp.txt
Hello, world.
Hi, python!
(2) r mode: write to the same file again
$ Cat file_0000py
Filename = "temp.txt"
F = open (filename, "w ")
F. write ("Be serious! \ N ")
F. write ("Not funny at all! \ N ")
F. close ()
$ Python file_1_py
$ Cat temp.txt
Be serious!
Not funny at all!
It can be seen that the content in the previous file has been cleared.
(3) a mode: write to the same file

$ Cat file_a.py
Filename = "temp.txt"
F = open (filename, "")
F. write ("hello, world. \ n ")
F. write ("hi, python! \ N ")
F. close ()
$ Python file_a.py
$ Cat temp.txt
Be serious!
Not funny at all!
Hello, world.
Hi, python!
2.2 read mode
You can read files opened in read mode. If a non-existent file is opened in read mode, an error is returned (IOError: [Errno 2] No such file or directory ).

(1) read

As mentioned above, read reads the content of the entire file by default and returns it.

$ Cat file_r.py
Filename = "temp.txt"
F = open (filename, "r ")
Print f. read ()
F. close ()
$ Python file_r.py
Be serious!
Not funny at all!
Hello, world.
Hi, python!
(2) readline
Readline ([size])-> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF.
Read a row of the file, retain the line break, and return an empty string at the end of the file.
$ Cat file_readline.py
Filename = "temp.txt"
F = open (filename, "r ")
Line = f. readline ()
While line: // the last blank line will be printed.
# Readline will retain an enter, so add', 'at the end to remove the enter of print
Print line,
Line = f. readline ()
F. close ()
$ Cat temp.txt
Be serious!
Not funny at all!
Hello, world.
Hi, python!
// There is a blank line
$ Python file_readline.py
Be serious!
Not funny at all!
Hello, world.
Hi, python!
// Empty rows will be displayed at the end
(3) readlines
Readlines ([size])-> list of strings, each a line from the file.
Call readline () repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned.
Call readline repeatedly to read all rows in the file to a list.
$ Cat file_readlines.py
Filename = "temp.txt"
F = open (filename, "r ")
Lines = f. readlines ()
For line in lines:
Print line,
F. close ()
$ Cat temp.txt
Be serious!
Not funny at all!
Hello, world.
Hi, python!
// There is a blank line
$ Python file_readlines.py
Be serious!
Not funny at all!
Hello, world.
Hi, python!
// Empty rows will be displayed at the end
Now, you can use python to perform basic file operations. The complex requirements will be further supplemented.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.