search
HomeBackend DevelopmentPython TutorialGet file operations in Python

Get file operations in Python

Nov 09, 2020 pm 05:36 PM
pythonFile 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复制代码</module></stdin>

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() #关闭文件         
复制代码
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复制代码

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']复制代码

写入文件

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

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

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

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

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

运行后会发现之前写的关注《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')      
复制代码

指针操作

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

句柄(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' 
复制代码

上下文管理

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

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

#输出如下
False
True复制代码

如何批量读取多个文件

下面,批量读取某文件夹下的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)复制代码

下面将批量读取文件夹下的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()复制代码

其实在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()复制代码

题目:生成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()复制代码

相关免费学习推荐: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
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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