How to load and process Python files?
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)
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 Falseos.mkdir()
: Create path
2. Arrange the file names in a list
file_list = os.listdir(dir_path)
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)
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)
[1, 3, 5, 7, 9]
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() # 关闭文件,这个可以是个好习惯哦
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()
1.3 The meaning of each file label
Access Mode | Description |
---|---|
Open the file read-only . The file pointer will be placed at the beginning of the file. This is the default mode. | |
Open a file for writing only. If the file already exists, it is overwritten. If the file does not exist, create a new file. | |
Open 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. | |
Open 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. | |
Open 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. | |
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. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing. | |
Open a file for reading and writing. The file pointer will be placed at the beginning of the file. | |
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. | |
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. | |
Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. | |
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. | |
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. |
#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()
#coding=utf-8 f = open('11.txt', 'r') content = f.readline() print("1:%s" % content) content = f.readline() print("2:%s" % content) f.close()
# 提示输入文件 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()
import os os.rename("毕业论文.txt", "毕业论文-最终版.txt")
import os os.remove("毕业论文.txt")
import os os.mkdir("张三")
import os os.getcwd()
import os os.chdir("../")
import os os.listdir("./")
import os os.rmdir("张三")
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]['name'], info_list[modify_num]['tel'],info_list[modify_num]['qq'])) info_list[modify_num]['name'] = input("请输入新的姓名:") info_list[modify_num]['tel'] = input("请输入新的手机号:") info_list[modify_num]['qq'] = input("请输入新QQ:") else: print("输入序号有误,请重新输入") def search_info(): """查询学生信息""" search_name = input("请输入要查询的学生姓名:") for temp_info in info_list: if temp_info['name'] == search_name: print("查询到的信息如下:") print("name:%s, tel:%s, QQ:%s" % (temp_info['name'], temp_info['tel'], temp_info['qq'])) 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['name'], temp['tel'], temp['qq'])) 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()
with open('新1.csv', 'a', encoding='utf-8-sig', newline='') as f: csv_writer = csv.writer(f, delimiter=',') csv_writer.writerow( [str(name), str(zijin), str(guimo), str(jingli), str(phone1), str(phone2),str(chanpin)])
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

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.

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.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

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.

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.
