Table of Contents
Encoding method
File operation API
读取文件
写入文件
指针操作
上下文管理
如何批量读取多个文件
练习
Home Backend Development Python Tutorial Get file operations in Python

Get file operations in Python

Nov 09, 2020 pm 05:36 PM
python File operations

Python Video Tutorial column introduces related file operations.

Get file operations in Python

Any language is inseparable from the operation of files, so how does the Python language operate and manage files.

Encoding method

The history of encoding method is roughly ASCII ->gb2312->unicode-> utf-8, for detailed information during this period, please refer to Baidu

to give a small example of encoding and decoding. Remember that Chinese can be used for GBK and utf-8 Encoding, in GBk one Chinese character corresponds to two bytes, in utf-8 one Chinese character corresponds to three bytes, Chinese cannot be processed ASCIIcoding.

>>> '刘润森'.encode('GBK')
b'\xc1\xf5\xc8\xf3\xc9\xad'
>>> '刘润森'.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
>>> 'Runsen'.encode('ascii')
b'Runsen'
>>> "刘润森".encode('utf-8')
b'\xe5\x88\x98\xe6\xb6\xa6\xe6\xa3\xae'
>>> '刘润森'.encode('GBK').decode('GBK')
'刘润森'
>>> '刘润森'.encode('GBK').decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte复制代码
Copy after login

If the encoding and decoding formats are inconsistent, garbled characters may appear. encode means encoding and decode means decoding.

File operation API

The following is the specific API for Python file operation.

##openopenreadreadwritewritecloseClosereadlineSingle line readingreadlinesMulti-line readingseekFile pointer operationtellRead the current Pointer position
Method Meaning
#Open file

Python's

open() function has several parameters available when opening a file. However, only the first two parameters are most commonly used.

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Note that the first one is mandatory, the rest are optional. If you do not add the mode parameter, the file will be opened in read-only mode in Python.

encoding: You don’t need to write it. If no parameters are written, the default codebook is the default codebook of the operating system. Windows defaults to gbk, Linux defaults to utf-8, and mac defaults to utf-8.

f=open('test.txt',encoding='utf-8')   #打开文件
data=f.read()  #读取文件
print(data)
f.close() #关闭文件         
复制代码
Copy after login
mode

modemeaningr Text mode, read rb Binary mode, read wText mode, write wb Binary mode, write aText mode, append ab Binary mode, append Readable and writable

读取文件

代码中用到的文件文件操作的1.txt 文件内容如下:

关注《Python之王》公众号
作者:Runsen复制代码
Copy after login

readline(),使用该方法时,需要指定打开文件的模式为r或者r+;

readlines(),读取全部行.返回一个列表,列表中的每个元素是原文件的每一行。如果文件很大,占内存,容易崩盘。

# 打开文件进行读取
f = open("1.txt","r",encoding='utf-8')
# 根据大小读取文件内容
print('输出来自 read() 方法\n',f.read(2048))
# 关闭文件
f.close()
# 打开文件进行读写
f = open("1.txt","r+",encoding='utf-8')
# 读取第2个字和第2行行的文件内容
print('输出来自 readline() 方法\n',f.readline(2))
print('输出来自 readlines() 方法\n',f.readlines(2))
# 关闭文件
f.close()
# 打开文件进行读取和附加
f = open("1.txt","r",encoding='utf-8')
# 打开文件进行读取和附加
print('输出来自 readlines() 方法\n',f.readlines())
# 关闭文件
f.close()

# 输出如下
输出来自 read() 方法
 关注《Python之王》公众号
作者:Runsen
输出来自 readline() 方法
 关注
输出来自 readlines() 方法
 ['《Python之王》公众号\n']
输出来自 readlines() 方法
 ['关注《Python之王》公众号\n', '作者:Runsen']复制代码
Copy after login

写入文件

下面只介绍清除写 w追加写 a

案例:将关注《Python之王》公众号写入 test.txt 文件中

# mode=w 没有文件就创建,有就清除内容,小心使用
with open('test.txt', 'w', encoding='utf-8') as fb:
      fb.write('关注《Python之王》公众号\n')  
复制代码
Copy after login

下面再将作者:Runsen写入test.txt 文件中

with open('test.txt', 'w', encoding='utf-8') as fb:
      fb.write('作者:Runsen\n')  
复制代码
Copy after login

运行后会发现之前写的关注《Python之王》公众号内容修改为作者:Runsen,因为 w模式会清除原文件内容,所以小心使用。只要使用了w,就要一次性写完。

追加写 a

案例:将静夜思这首诗追加到 test.txt 文件中

# mode=a 追加到文件的最后
with open('test.txt', 'a', encoding='utf-8') as fb:
      fb.write('关注《Python之王》公众号\n')  
with open('test.txt', 'a'encoding='utf-8') as fb:
      fb.write('作者:Runsen\n')      
复制代码
Copy after login

指针操作

事物或资源都是以文件的形式存在,比如消息、共享内存、连接等,句柄可以理解为指向这些文件的指针。

句柄(handle)是一个来自编译原理的术语,指的是一个句子中最先被规约的部分,所以带有一个「句」字。

句柄的作用就是定位,两个APi还是tell和seek。

tell返回文件对象在文件中的当前位置,seek将文件对象移动到指定的位置,传入的参数是offset ,表示移动的偏移量。

下面通过示例对上述函数作进一步了解,如下所示:

with open('test.txt', 'rb+') as f:
    f.write(b'Runsen')
    # 文件对象位置
    print(f.tell())
    # 移动到文件的第四个字节
    f.seek(3)
    # 读取一个字节,文件对象向后移动一位
    print(f.read(1))
    print(f.tell())
    # whence 为可选参数,值为 0 表示从文件开头起算(默认值)、值为 1 表示使用当前文件位置、值为 2 表示使用文件末尾作为参考点
    # 移动到倒数第二个字节
    f.seek(-2, 2)
    print(f.tell())
    print(f.read(1))
    
#输出如下
6
b's'
4
50
b'\r' 
复制代码
Copy after login

上下文管理

我们会进行这样的操作:打开文件,读写,关闭文件。程序员经常会忘记关闭文件。上下文管理器可以在不需要文件的时候,自动关闭文件,使用with open即可。

# with context manager
with open("new.txt", "w") as f:
    print(f.closed)
    f.write("Hello World!")
print(f.closed)

#输出如下
False
True复制代码
Copy after login

如何批量读取多个文件

下面,批量读取某文件夹下的txt文件

file_list = ['1.txt', '2.txt', '3.txt','4.txt']
for path in file_list:
    with open(path, encoding='utf-8') as f:
        for line in f:
            print(line)复制代码
Copy after login

下面将批量读取文件夹下的txt文件的内容,合并内容到一个新文件5.txt中,具体实现的代码如下。

import os
#获取目标文件夹的路径
filedir = os.getcwd()+'\\'+'\\txt'
#获取当前文件夹中的文件名称列表
filenames = []
for i in os.listdir(filedir):
    if i.split(".")[-1] == 'txt':
        filenames.append(i)
#打开当前目录下的5.txt文件,如果没有则创建
f = open('5.txt','w')
#先遍历文件名
for filename in filenames:
    filepath = filedir+'\\'+filename
    #遍历单个文件,读取行数
    for line in open(filepath,encoding='utf-8'):
        f.writelines(line)
        f.write('\n')
#关闭文件
f.close()复制代码
Copy after login

其实在Window中只需要cd 至目标文件夹,即你需要将所有想要合并的txt文件添加至目标文件夹中,执行如下DOS命令  type *.txt > C:\目标路径\合并后的文件名.txt

练习

题目:创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数,题目来源:牛客

import random

f = open(‘data.txt’,‘w+’)
for i in range(100000):
  f.write(str(random.randint(1,100)) + ‘\n’)
  f.seek(0)
  print(f.read())
  f.close()复制代码
Copy after login

题目:生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B,题目来源:牛客

import random
import string

def create_mac():
  MAC='01-AF-3B'
  hex_num =string.hexdigits #0123456789abcdefABCDEF
  for i in range(3):
    n = random.sample(hex_num,2)
    sn = '-' + ''.join(n).upper()
    MAC += sn
  return MAC

def main():
  with open('mac.txt','w') as f:
    for i in range(100):
      mac = create_mac()
      print(mac)
      f.write(mac+'\n')

main()复制代码
Copy after login

相关免费学习推荐:python视频教程

The above is the detailed content of Get file operations in Python. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles