Home > Backend Development > Python Tutorial > How to load and process Python files?

How to load and process Python files?

王林
Release: 2023-05-09 21:01:08
forward
1467 people have browsed it

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!

Related labels:
source:yisu.com
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