python学习中遇到问题汇总
程序员文章站
2022-05-31 16:17:26
...
对字典组成的列表进行排序
order=sorted(listd,key=operator.itemgetter(“num”))
跳过第一次循环
head=next(table)
获取文件名
取文件的绝对路径os.path.abspath(sys.argv[0])或os.path.abspath(file)
os.path.split(文件绝对路径),[0]所在文件夹,[1]文件名
split(".")[0]获取去除后缀的文件名
filename=os.path.split(os.path.abspath(sys.argv[0]))[1].split(".")[0]
批量修改路径下CSV文件内容
递归查找目录下所有以.csv结尾的文件,以绝对路径组成列表:
os.listdir(绝对路径)列出文件夹下所有文件
os.path.isdir(绝对路径)判断是否为文件夹,使用相对路径判断,有时会出错
file.endswith(".csv")判断文件是否以.csv结尾
使用replace(old,new)进行文件内容修改
修改后的内容写入新文件
删除老文件os.remove(老文件)
将新文件改名为老文件os.rename(新文件,老文件)
import os
import csv
class csv_replace():
def __init__(self, old, new, ext):
self.old = old
self.new = new
self.ext = ext
self.filelist=[]
def csvtolist(self,data_path):
files = os.listdir(data_path)
# print(files)
for file in files:
if os.path.isdir(os.path.join(data_path,file)):
# print(os.listdir(file))
file1 = data_path + "\\" + file
self.csvtolist(file1)
elif file.endswith(self.ext):
absfile = data_path + "\\" + file
self.filelist.append(absfile)
# print(filelist)
return self.filelist
def replace_func(self,csvtolist):
for i in csvtolist:
with open(i, "r") as file1, open(i + "_new", "w", newline="") as file2:
table = csv.reader(file1)
writer = csv.writer(file2)
for row in table:
if self.old == row[1]:
row[1] = row[1].replace(self.old, self.new)
writer.writerow(row)
os.remove(i)
os.rename(i+"_new", i)
if __name__ == "__main__":
data_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + "\\datafile\\"
# old = "com.youdao.note:id/enter_app"
# new = "com.youdao.note:id/enter_app_new"
old = "com.youdao.note:id/enter_app_new"
new = "com.youdao.note:id/enter_app"
ext = ".csv"
obj = csv_replace(old, new, ext)
filelist=obj.csvtolist(data_path)
obj.replace_func(filelist)
查看浏览器内核
https://liulanmi.com/labs/core.html