Home  >  Article  >  Backend Development  >  Implementation code for Python file reading, writing and saving operations

Implementation code for Python file reading, writing and saving operations

不言
不言Original
2018-09-13 16:37:531486browse

The content of this article is about the implementation code of Python file reading, writing and saving operations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Record the process of using Python to read and write files for the first time. Although it is very simple, there are actually some things to pay attention to when implementing it for the first time.

Read operation of a single file:

Let’s first assume a requirement as follows:

Read a test.txt file

Delete specified characters After understanding the requirements of the previous text

, let’s start writing the code. The code is very simple. Just go to all of them directly, and see the comments for details:

import sys
filePath = "/Users/xxxxxx/Desktop/test.txt"
# 打开文件
files = open(filePath, 'r')
# 转成list
f_list = files.readlines()
tempIndex = 0
# 对f_list 循环 每个index对应一行数据
for index in range(len(f_list)):
    # temp是获取一行的数据
    temp = f_list[index]
    # 判断"test"是不是temp这行数据的首位 如果是首位 result为true
    result = temp.find("test") == 0
    if result:
        # 如果是首位 这就是我们要删除的位置 获取他的index
        tempIndex = index
        break
# 存放新数据
tempContainer = []

for index in range(len(f_list)):
    if index > tempIndex:
        # tempIndex之前的数据我们不处理,把tempindex之后的数据存到新的list里面
        tempContainer.append(f_list[index])
# 这就获得了我们需要的新数据
print(tempContainer)

The above code completes the requirements, it is very simple. There are a few points to note:

The data obtained directly using open cannot be processed, so first convert it to data that can be processed, such as a list or dictionary, etc.

Python's open is similar to C's, with various states such as r, r, w, w, etc. See the detailed introduction

Common operating methods of the open function
1. r opens only To read a file, the file must exist.
2. r opens a readable and writable file, which must exist.
3. w opens a write-only file. If the file exists, the file length is cleared to 0, that is, the file content will disappear. If the file does not exist, create the file.
4. w opens a readable and writable file. If the file exists, the file length will be cleared to zero, that is, the file content will disappear. If the file does not exist, create the file.

Read, write and save multiple files

Suppose a requirement is as follows:

  • Multiple files must be processed

  • The processing method is similar to the above test.txt

  • After processing, save it to a new folder

In fact, this requirement is essentially just one more write operation than a single file read operation. The other thing is to go around the logic a little bit

  • How to operate multiple files at the same time

  • And then how to save it into multiple files

It is definitely not possible to operate file by file, it is too troublesome. Let me talk about my implementation idea:

  • Put the files in a folder

  • Get all the file names in this folder and splice them into the file path

  • Then create a new empty folder, use the new empty folder plus the original file name to concatenate it into a new path and write it into it

The code below:

import os

# 初始的文件夹路径
filePath = "/Users/xxxxxxxx/Desktop/fileDocument"
# 存放新文件的空白文件夹
newFilePath = "/Users/xxxxxxxx/Desktop/newFileDocument"
# 获取文件夹下所有文件名
fileNames = os.listdir(filePath)
for file in fileNames:
    # 如果当前的文件名包含了'txt',就当它是正确的文件(并不严谨)
    if file.find("txt") >= 0:
        # 拼接成我们要读取的完整路径
        fileFullPath = filePath + "/" + file
        # open 函数 默认是 'r'类型 ,
        singleFile = open(fileFullPath)
        # 转换成list数据
        singleFile_list = singleFile.readlines()

        tempIndex = 0
        for index in range(len(singleFile_list)):
            temp = singleFile_list[index]
            result = temp.find("min") == 0
            if result:
                tempIndex = index
                break
        # 拼接新的文件路径
        newSingleFileFullPath = newFilePath + "/" + file
        # 以 w 方式打开新的空白文件
        newFile = open(newSingleFileFullPath, 'w')
        for index in range(len(singleFile_list)):
            if index > tempIndex:
                # 写入tempindex行之后的数据
                newFile.writelines(singleFile_list[index])
        newFile.close()

The above code actually has nothing to introduce, it is just a for loop and the logic is the same as a single file read operation, except for an additional write operation.

Related recommendations:

Read and write operation code for PHP files

Details of Python completing reading and saving file classes Introduction

Python implements reading the file names of all files in the directory and saving them to txt files code

The above is the detailed content of Implementation code for Python file reading, writing and saving operations. 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