search
HomeBackend DevelopmentPython TutorialBasic operation methods of python file input and output

1. Python File I/O
This chapter only describes all basic I/O functions. For more functions, please refer to the Python standard document.

2. Print to the screen
The simplest output method is to use the print statement. You can pass it zero or more values ​​separated by commas. The expression. This function converts the expression you pass into a string expression and writes the result to standard output as follows:

Example 1:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
print "python 是一门面向对象语言"

Run Example 1 The results are as follows:

python 是一门面向对象语言

3. Read keyboard input
Python provides two built-in functionsRead a line of text from standard input, the default standard input It's the keyboard. As follows:

  • raw_input

  • input

raw_input function
The raw_input([prompt]) function reads a line from the standard input and returns a string (removing the trailing newline character):
Example 2:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
strs = raw_input("请输入你想输入的字符串:")
print "您输入的字符串是:",strs

Example 2 Running results:

请输入你想输入的字符串:python
您输入的字符串是: python

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

Example 3:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx

inputStr = input("可以输入表达式:")
print "运行输入的结果:", inputStr

Example 3 Running results:

可以输入表达式:[x*4 for x in (2,3,4)]
运行输入的结果: [8, 12, 16]

4. Open and close the file
Now, you can submit the standard Input and output are read and written. Now, let's see how to read and write the actual data file.
 Python provides the necessary functions and methods to perform basic file operations by default. You can do most file operations with the file object.
open function
You must first use Python’s built-in open() function to open a file and create a file object before the relevant methods can call it for reading and writing.
Syntax:

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

The details of each parameter are as follows:

  • file_name: file_nameVariable is a The string value of the name of the file you want to access.

  • access_mode: access_mode determines the mode of opening the file: read-only, write, append, etc. See the complete list of all possible values ​​below. This parameter is optional and the default file access mode is read-only (r).

  • buffering: If the buffering value is set to 0, there will be no buffering. If the value of buffering is 1, lines will be buffered when accessing the file. If the buffering value is set to an integer greater than 1, it indicates that this is the buffer size of the register area. If it takes a negative value, the buffer size of the register area is the system default.

Full list of different modes for opening files:
Mode Description

  1. r Open the file in read-only mode . The file pointer will be placed at the beginning of the file. This is the default mode.

  2. rb Opens a file in binary format for reading only. The file pointer will be placed at the beginning of the file. This is the default mode.

  3. r+ Opens a file for reading and writing. The file pointer will be placed at the beginning of the file.

  4. rb+ Opens a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.

  5. w Open a file for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file.

  6. wb Opens a file in binary format for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file.

  7. w+ Opens a file for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file.

  8. wb+ Opens a file in binary format for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file.

  9. a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing.

  10. ab Opens 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, new content will be written after existing content. If the file does not exist, create a new file for writing.

  11. a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。

  12. ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

File对象的属性
  一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。
  以下是和file对象相关的所有属性的列表:
  属性 描述

  • file.closed 返回true如果文件已被关闭,否则返回false。

  • file.mode 返回被打开文件的访问模式。

  • file.name 返回文件的名称。

  • file.softspace 如果用print输出后,必须跟一个空格符,则返回0。否则返回1。

示例4

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
filetest = open("file.txt", "wb")

print "文件是否关闭:", filetest.closed
print "文件模式:", filetest.mode
print "文件名称:", filetest.name
print "是否强制在末尾加空格:", filetest.softspace

示例4 运行结果:

文件是否关闭: False
文件模式: wb
文件名称: file.txt
是否强制在末尾加空格: 0

close()方法
  File 对象的 close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。
  当一个文件对象的引用被重新指定给另一个文件时,Python 会关闭之前的文件。用 close()方法关闭文件是一个很好的习惯。
  语法:

fileObject.close();

示例5

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
filetest = open("file.txt", "wb")

print "文件是否关闭:", filetest.closed
print "文件模式:", filetest.mode
print "文件名称:", filetest.name
print "是否强制在末尾加空格:", filetest.softspace
print "关闭文件!"
filetest.close()  # 关闭文件
print "文件关闭成功!"

示例5 结果:

文件是否关闭: False
文件模式: wb
文件名称: file.txt
是否强制在末尾加空格: 0
关闭文件!
文件关闭成功!

5.读写文件
  file对象提供了一系列方法,能让我们的文件访问更轻松。来看看如何使用read()和write()方法来读取和写入文件。
  write()方法
  write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
  write()方法不会在字符串的结尾添加换行符('\n'):
  语法:

fileObject.write(string);

在这里,被传递的参数是要写入到已打开文件的内容。
 示例6

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
filetest = open("file.txt", "wb")
filetest.write("python 编程语言可以用到很多地方")
print "关闭文件!"
filetest.close()  # 关闭文件
print "文件关闭成功!"
print "重新打开读取文件!"
filetest = open("file.txt", "rb")
strs = filetest.read(1024)
print "文件我内容是:",strs

示例6 运行结果:

关闭文件!
文件关闭成功!
重新打开读取文件!
文件我内容是: python 编程语言可以用到很多地方

    read()方法
  read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
  语法:

fileObject.read([count])

  在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。

  用例参考示例6 

6文件位置

  • tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后。

  • seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。

  • 如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。

示例7:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
filetest = open("file.txt", "wb")
filetest.write("python 编程语言可以用到很多地方")
# 打开文件
filetest = open("file.txt", "rb")
strs = filetest.read(10)
print "文件内容是:", strs
# 定位文件位置
p = filetest.tell()
print "文件当前位置", p

# 重新设置文件读取的位置
filetest.seek(0, 0)
print "将文件位置重新设置成功!!!"

print "重新设置指针位置之后读取的文件"
strs = filetest.read(10)
print "文件内容是:", strs


print "关闭文件!"
filetest.close()  # 关闭文件
print "文件关闭成功!"

示例7运行结果:

文件内容是: python 编
文件当前位置 10将文件位置重新设置成功!!!
重新设置指针位置之后读取的文件
文件内容是: python 编
关闭文件!
文件关闭成功!

7.重命名和删除文件
  Python的os模块提供了帮你执行文件处理操作的方法,比如重命名和删除文件。
  要使用这个模块,你必须先导入它,然后才可以调用相关的各种功能。
  rename()方法:
  rename()方法需要两个参数,当前的文件名和新文件名。
  语法:

os.rename(current_file_name, new_file_name)

示例8:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
import os
filetest = open("myfile.txt", "wb")
# 文件写入内容
filetest.write("python 基础学习")
# 未年检关闭!
filetest.close()
# 文件重新命名
os.rename("myfile.txt", "renamefile.txt")

print "重新命名后的文件名称是:", filetest.name
# 以只读方式打开重命名文件
fileremane = open("renamefile.txt", "r")
strs = fileremane.read(100)
print "文件名称:", fileremane.name
print "读取修改后文件的内容是:", strs

示例 8 运行结果:

重新命名后的文件名称是: myfile.txt
文件名称: renamefile.txt
读取修改后文件的内容是: python 基础学习

注意:如果目录下面已经存在相关名称文件,那么重命名就会出现异常

  remove()方法
  你可以用remove()方法删除文件,需要提供要删除的文件名作为参数。
  语法:

os.remove(file_name)

示例 9

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
import os
filetest = open("myfile.txt", "wb")
# 文件写入内容
filetest.write("python 基础学习")
# 未年检关闭!
filetest.close()
# 删除文件
os.remove("myfile.txt")
# 重新读取删除掉的文件
filetest = open("myfile.txt", "rb")
# 打印出文件内容
print "文件内容是:", filetest.read(10)

示例 9 运行结果

Traceback (most recent call last):
  File "E:/python/hello/untitled3/filetest.py", line 14, in <module>
    filetest = open("myfile.txt", "rb")
IOError: [Errno 2] No such file or directory: 'myfile.txt'</module>

运行结果:因为读取了一个删除掉的文件,所以会报异常

8. Python里的目录
  所有文件都包含在各个不同的目录下,不过Python也能轻松处理。os模块有许多方法能帮你创建,删除和更改目录。
  mkdir()方法
  可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数。
  语法:

os.mkdir("newdir")

  chdir()方法
  可以用chdir()方法来改变当前的目录,修改目录路径。chdir()方法需要的一个参数是你想设成当前目录的目录名称。
  语法:

os.chdir("newdir")

   getcwd()方法

  getcwd()方法显示当前的工作目录。
  语法:

os.getcwd()

  rmdir()方法
  rmdir()方法删除目录,目录名称以参数传递。
  在删除这个目录之前,它的所有内容应该先被清除。
  语法:

os.rmdir('dirname')

示例10:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2016/9/25 15:12
# @Author  : wwyx
import os
# 创建一个目录
os.mkdir("mydir")
# 获取当前目录
nowdir = os.getcwd()
print "当前目录:", nowdir
# 重新定位目录,修改目录路径
os.chdir("mydir")
# 获取修改后的目录路径
updatedir = os.getcwd()
print "修改后的当前目录是:",updatedir
ind = updatedir.rfind("\\")
print "截取后的字符串", ind
print "type:", type(updatedir)
newdir = updatedir[0:int(ind)]
print "new dir", newdir
# 重新定位目录,修改目录路径
os.chdir(newdir)
# 获取修改后的目录路径
updatedir = os.getcwd()
print "修改后的当前目录是:",updatedir
# 删除目录
os.rmdir("mydir")
# 获取删除后的目录路径
deletedir = os.getcwd()
print "修改后的当前目录是:",deletedir

示例10 运行结果:

当前目录: E:\python\hello\untitled3
修改后的当前目录是: E:\python\hello\untitled3\mydir
截取后的字符串 25type: <type>new dir E:\python\hello\untitled3
修改后的当前目录是: E:\python\hello\untitled3
修改后的当前目录是: E:\python\hello\untitled3</type>

9.文件、目录相关的方法
  三个重要的方法来源能对Windows和Unix操作系统上的文件及目录进行一个广泛且实用的处理及操控,如下:

  • File 对象方法: file对象提供了操作文件的一系列方法。

  • OS 对象方法: 提供了处理文件及目录的一系列方法。

The above is the detailed content of Basic operation methods of python file input and output. 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
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment