Python读写文件
2021/11/30 22:06:17
本文主要是介绍Python读写文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.从一个文件中读取内容(比如有3列内容),然后再新增加2列字段,并存放在列表中(一共5列)。
2.打开一个新的文件,循环包含有5列表字段的列表,并将内容写进新的文件。
import random def writecChannelIdFile(fp, writeFile): channel_ids = {'125002805': "135379412029940069", '125102805': "287200733847731473"} # 125002805:微信 125102805:支付宝 channel_id = ['125002805', '125102805'] with open(fp, "r") as ff: myReadFile = ff.readlines() orderList = [] for line in myReadFile: channel_id_choice = random.choice(channel_id) #随机取列表的内容(一定要放在for循环里面) newLine = line.replace("\n", ",")+channel_id_choice +"," + channel_ids[channel_id_choice] print(newLine) orderList.append(newLine) with open(writeFile, 'w')as wf: for order in orderList: print(order) wf.write(order+"\n") if __name__ == "__main__": fp = r"D:\xxx\xxx\xxx\a.txt" #读取该路径下的a.txt文件 writeFile = r"D:\xxx\xxx\xxx\b.txt" #会在该路径下生成一个b.txt的文件 writecChannelIdFile(fp, writeFile)
这篇关于Python读写文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战