Home  >  Article  >  Backend Development  >  How to output file contents in python

How to output file contents in python

(*-*)浩
(*-*)浩Original
2019-07-05 11:37:3116423browse

A file is just a continuous sequence of bytes. Data transmission often uses byte streams, regardless of whether the byte stream is composed of a single byte or a large block of data.

How to output file contents in python

You must first use the Python built-in The open() function opens a file and creates a file object. Only the relevant methods can call it for reading and writing. (Recommended learning: Python video tutorial)

file_object=open(file_name,access_mode='r',buffering=-1)

file_name is a string containing the name of the file to be opened. It can be a relative path or an absolute path.

The access_mode optional variable is also a string, representing the mode in which the file is opened.

'r' represents: reading;

'w' represents: writing;

'a' represents: append;

read() method

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

Syntax:

fileObject.read([count])

Here, the parameter passed is the byte count to be read from the opened file. This method starts reading from the beginning of the file, and if count is not passed in, it will try to read as much as possible, probably until the end of the file.

Example:

Here we use the foo.txt file created above.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10)
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close()

Output:

读取的字符串是 :  www.xxxxxx.com

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to output file contents in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn