Basic operation methods of python file input and output

高洛峰
Release: 2017-03-21 13:51:20
Original
1585 people have browsed it

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 是一门面向对象语言"
Copy after login

Run Example 1 The results are as follows:

python 是一门面向对象语言
Copy after login

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
Copy after login

Example 2 Running results:

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

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
Copy after login

Example 3 Running results:

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

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]
Copy after login

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
Copy after login

示例4 运行结果:

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

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

fileObject.close();
Copy after login

示例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 "文件关闭成功!"
Copy after login

示例5 结果:

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

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

fileObject.write(string);
Copy after login

在这里,被传递的参数是要写入到已打开文件的内容。
示例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
Copy after login

示例6 运行结果:

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

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

fileObject.read([count])
Copy after login

  在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入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 "文件关闭成功!"
Copy after login

示例7运行结果:

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

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

os.rename(current_file_name, new_file_name)
Copy after login

示例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
Copy after login

示例 8 运行结果:

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

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

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

os.remove(file_name)
Copy after login

示例 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)
Copy after login

示例 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: &#39;myfile.txt&#39;
Copy after login

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

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

os.mkdir("newdir")
Copy after login

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

os.chdir("newdir")
Copy after login

  getcwd()方法

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

os.getcwd()
Copy after login

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

os.rmdir(&#39;dirname&#39;)
Copy after login

示例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
Copy after login

示例10 运行结果:

当前目录: E:\python\hello\untitled3
修改后的当前目录是: E:\python\hello\untitled3\mydir
截取后的字符串 25type: <type &#39;str&#39;>new dir E:\python\hello\untitled3
修改后的当前目录是: E:\python\hello\untitled3
修改后的当前目录是: E:\python\hello\untitled3
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template