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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 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.

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 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 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.

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.

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.

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.

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.
