Table of Contents
File loading and processing
1. Check whether the file path of python
2. Arrange the file names in a list
3. Filter files that do not meet the requirements
4. Used to convert tuples into lists
5. Open the file codeces, open()
6. readlines()
7, strip()
python file processing (summary)
1. txt file
Home Backend Development Python Tutorial How to load and process Python files?

How to load and process Python files?

May 09, 2023 pm 09:01 PM
python

File loading and processing

1. Check whether the file path of python

about file loading and processing methods exists. If it does not exist, create this path.

#如果不存在路径,就创建一个这样的路径
    if not os.path.exists(exp_path):
        os.mkdir(exp_path)
Copy after login
  • os.path.exists(): Determine whether the file in the brackets exists. The file in the brackets can be the file path. If it exists, return True , does not exist and returns False

  • os.mkdir(): Create path

2. Arrange the file names in a list

file_list = os.listdir(dir_path)
Copy after login

3. Filter files that do not meet the requirements

filter() function is used to filter the sequence, filter out elements that do not meet the conditions, and return a sequence composed of elements that meet the conditions. New list

filter(function, iterable)
Copy after login
  • function -- Determination function.

  • iterable -- Iterable object

def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)
Copy after login
[1, 3, 5, 7, 9]
Copy after login

4. Used to convert tuples into lists

  • list()

^(* ̄(oo) ̄)^

Tuples and Lists are very similar, the difference is that the element values ​​of the tuple cannot be modified.

Tuples are placed in brackets, lists are placed in square brackets

5. Open the file codeces, open()

Check the information After testing and experimenting, we found that the function is similar to that of open(), but when crawling or other methods are used to obtain data and write it into a file, there will be a problem of inconsistent encoding, so it is generally converted to Unicode encoding.

In short, it is more convenient to use codeces and open().

6. readlines()

Read the entire file content line by line each time, put the read content into a list, and return the list type

7, strip()

Read the entire file content line by line each time, put the read content into a list, and return the list type

python file processing (summary)

1. txt file

1.1 Reading txt file

        with open("11.txt", 'r') as file:
            for l in file:
                idnos.append(l.replace('\n',''))
        f.close()  # 关闭文件,这个可以是个好习惯哦
Copy after login

1.2 Writing txt without overwriting

            with open("d.txt", 'a',encoding='utf-8') as file:
                file.write('\n' + '摘要:' + gaiyao)
                file.write('\n')
            file.close()
Copy after login

1.3 The meaning of each file label

##rOpen the file read-only . The file pointer will be placed at the beginning of the file. This is the default mode. wOpen a file for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file. aOpen 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. rbOpen 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. wbOpen 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. abOpen 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. r Open a file for reading and writing. The file pointer will be placed at the beginning of the file. w Open a file for reading and writing. If the file already exists, it is overwritten. If the file does not exist, create a new file. a Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, a new file is created for reading and writing. #rb Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. wb Open 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. ab Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, a new file is created for reading and writing.
Access ModeDescription
1.4 Read all the contents in txt line by line

#coding=utf-8
f = open('11.txt', 'r')
content = f.readlines()
print(type(content))
i=1
for temp in content:
    print("%d:%s" % (i, temp))
    i += 1
f.close()
Copy after login

1.5 Read the contents of the first two lines in txt

#coding=utf-8
f = open('11.txt', 'r')
content = f.readline()
print("1:%s" % content)
content = f.readline()
print("2:%s" % content)
f.close()
Copy after login

1.6 File Copy

# 提示输入文件
oldFileName = input("请输入要拷贝的文件名字:")
# 以读的方式打开文件
oldFile = open(oldFileName,'rb')
# 提取文件的后缀
fileFlagNum = oldFileName.rfind('.')
if fileFlagNum > 0:
    fileFlag = oldFileName[fileFlagNum:]
# 组织新的文件名字
newFileName = oldFileName[:fileFlagNum] + '[复件]' + fileFlag
# 创建新文件
newFile = open(newFileName, 'wb')
# 把旧文件中的数据,一行一行的进行复制到新文件中
for lineContent in oldFile.readlines():
    newFile.write(lineContent)
# 关闭文件
oldFile.close()
newFile.close()
Copy after login

1.7 File related operations

File rename

import os
os.rename("毕业论文.txt", "毕业论文-最终版.txt")
Copy after login

Delete file

import os
os.remove("毕业论文.txt")
Copy after login

Create folder

import os
os.mkdir("张三")
Copy after login

Get the current Directory

import os
os.getcwd()
Copy after login

Change the default directory

import os
os.chdir("../")
Copy after login

Get directory list

import os
os.listdir("./")
Copy after login

Delete folder

import os
os.rmdir("张三")
Copy after login

1.8 File Management - Student Management System

Note: Create a file first: info_data.data

import time
import os
# 定一个列表,用来存储所有的学生信息(每个学生是一个字典)
info_list = []
def print_menu():
    print("---------------------------")
    print("      学生管理系统 V1.0")
    print(" 1:添加学生")
    print(" 2:删除学生")
    print(" 3:修改学生")
    print(" 4:查询学生")
    print(" 5:显示所有学生")
    print(" 6:保存数据")
    print(" 7:退出系统")
    print("---------------------------")
def add_new_info():
    """添加学生信息"""
    global info_list
    new_name = input("请输入姓名:")
    new_tel = input("请输入手机号:")
    new_qq = input("请输入QQ:")
    for temp_info in info_list:
        if temp_info['name'] == new_name:
            print("此用户名已经被占用,请重新输入")
            return  # 如果一个函数只有return就相当于让函数结束,没有返回值
    # 定义一个字典,用来存储用户的学生信息(这是一个字典)
    info = {}
    # 向字典中添加数据
    info["name"] = new_name
    info["tel"] = new_tel
    info["qq"] = new_qq
    # 向列表中添加这个字典
    info_list.append(info)
def del_info():
    """删除学生信息"""
    global info_list
    del_num = int(input("请输入要删除的序号:"))
    if 0 <= del_num < len(info_list):
        del_flag = input("你确定要删除么?yes or no")
        if del_flag == "yes":
            del info_list[del_num]
    else:
        print("输入序号有误,请重新输入")
def modify_info():
    """修改学生信息"""
    global info_list
    modify_num = int(input("请输入要修改的序号:"))
    if 0 <= modify_num < len(info_list):
        print("你要修改的信息是:")
        print("name:%s, tel:%s, QQ:%s" % (info_list[modify_num][&#39;name&#39;],
            info_list[modify_num][&#39;tel&#39;],info_list[modify_num][&#39;qq&#39;]))
        info_list[modify_num][&#39;name&#39;] = input("请输入新的姓名:")
        info_list[modify_num][&#39;tel&#39;] = input("请输入新的手机号:")
        info_list[modify_num][&#39;qq&#39;] = input("请输入新QQ:")
    else:
        print("输入序号有误,请重新输入")
def search_info():
    """查询学生信息"""
    search_name = input("请输入要查询的学生姓名:")
    for temp_info in info_list:
        if temp_info[&#39;name&#39;] == search_name:
            print("查询到的信息如下:")
            print("name:%s, tel:%s, QQ:%s" % (temp_info[&#39;name&#39;],
                temp_info[&#39;tel&#39;], temp_info[&#39;qq&#39;]))
            break
    else:
        print("没有您要找的信息....")
def print_all_info():
    """遍历学生信息"""
    print("序号\t姓名\t\t手机号\t\tQQ")
    i = 0
    for temp in info_list:
        # temp是一个字典
        print("%d\t%s\t\t%s\t\t%s" % (i, temp[&#39;name&#39;], temp[&#39;tel&#39;], temp[&#39;qq&#39;]))
        i += 1
def save_data():
    """加载之前存储的数据"""
    f = open("info_data.data", "w")
    f.write(str(info_list))
    f.close()
def load_data():
    """加载之前存储的数据"""
    global info_list
    f = open("info_data.data")
    content = f.read()
    info_list = eval(content)
    f.close()
def main():
    """用来控制整个流程"""
    # 加载数据(1次即可)
    load_data()
    while True:
        # 1. 打印功能
        print_menu()
        # 2. 获取用户的选择
        num = input("请输入要进行的操作(数字):")
        # 3. 根据用户选择,做相应的事情
        if num == "1":
            # 添加学生
            add_new_info()
        elif num == "2":
            # 删除学生
            del_info()
        elif num == "3":
            # 修改学生
            modify_info()
        elif num == "4":
            # 查询学生
            search_info()
        elif num == "5":
            # 遍历所有的信息
            print_all_info()
        elif num == "6":
            # 保存数据到文件中
            save_data()
        elif num == "7":
            # 退出系统
            exit_flag = input("亲,你确定要退出么?~~~~(>_<)~~~~(yes or no) ")
            if exit_flag == "yes":
                break
        else:
            print("输入有误,请重新输入......")
        input("\n\n\n按回车键继续....")
        os.system("clear")  # 调用Linux命令clear完成清屏
# 程序的开始
main()
Copy after login

2. csv file operation

2.1 csv writing

with open(&#39;新1.csv&#39;, &#39;a&#39;, encoding=&#39;utf-8-sig&#39;, newline=&#39;&#39;) as f:
    csv_writer = csv.writer(f, delimiter=&#39;,&#39;)
    csv_writer.writerow(
        [str(name), str(zijin), str(guimo), str(jingli), str(phone1), str(phone2),str(chanpin)])
Copy after login

The above is the detailed content of How to load and process Python files?. 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)

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.

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: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

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.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

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.

See all articles