title = ['城市', '人口(万)'] info = [ ['南京', '850'], ['纽约', '2300'], ['东京', '3800'], ['巴黎', '1000'] ] with open('city1.csv', 'w', encoding='utf-8') as f: f.write(','.join(title) + '\n') for item in info: f.write(','.join(item) + '\n') with open('city1.csv', 'r', encoding='utf-8') as f: print(f.read().rstrip('\n')) with open('city1.csv', 'r', encoding='utf-8') as f: data = f.readlines() print('data: ') print(data) info = [line.rstrip('\n').split(',') for line in data] print('info: ') print(info)
2
3.
def is_valid(x): data=x if len(data)!=18: print(False) else: if ord(data[-1])==88 or 48<=ord(data[-1])<=57 : print(True) else: print(False)
with open('data3_id.txt', 'r', encoding='utf-8') as f: data=f.readlines() data=[line.strip().split(',') for line in data] ans=[] def isvalid(id): if len(id)!=18: return False else: for i in id: if '0'<=i<='9'or i=='X':continue return False return True for i in range(1,len(data)): if(isvalid(data[i][1])): ans.append([data[i][0],data[i][1][6:10]+'-'+data[i][1][10:12]+'-'+data[i][1][12:14]]) ans.sort(key=lambda x:x[1]) print(f'{data[0][0]},{data[0][1]}') for line in ans: print(f'{line[0]},{line[1]}')
4
5
import random n = int(input("输入随机抽点人数: ")) with open("data5.txt", encoding="utf-8") as f: data = f.readlines() data_ = data.copy() lucky_people = [] for i in range(n): x = random.choice(data_) lucky_people.append(x) data_.remove(x) with open("20220517.txt", "w+", encoding="utf-8") as f: f.writelines(lucky_people) f.seek(0) print(f.read())
import random print("{0:{1}{3}{2}}".format("抽点开始", "=", 40, "^")) active_input = True ls = [] while active_input: n = int(input("输入随机抽点人数: ")) if n == 0: break else: with open("data5.txt", encoding="utf-8") as f: data = f.readlines() data_ = data.copy() lucky_people = [] for i in range(n): x = random.choice(data_) lucky_people.append(x) data_.remove(x) with open("20220517.txt", "w+", encoding="utf-8") as f: f.writelines(lucky_people) f.seek(0) print(f.read()) ls += lucky_people with open("20220517.txt", "w", encoding="utf-8") as f: f.writelines(ls) print("{0:{1}{3}{2}}".format("抽点结束", "=", 40, "^"))
6
import os print(os.getcwd()) py_file_list = [ file for file in os.listdir() if file.endswith('.py') ] for number, file in enumerate(py_file_list, 1): print(f'{number:-3d}. {file}')