Python文件读写:把多个文件写入一个文件

效果说明

1.py

print("This is file1")

2.py

print("This is file2")

3.py

print("This is file3")

👉
all.txt

1.py
	print("This is file1")
2.py
	print("This is file2")
3.py
	print("This is file3")

这样就可以在sublime text里面折叠了嘻嘻

实现代码</

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,可以使用 `multiprocessing` 模块来实现多进程读写文件。 以下是一个示例代码,其中有两个进程,一个进程用于写入数据到文件中,另一个进程用于读取文件中的数据: ```python import multiprocessing # 写入数据到文件的进程 def write_data(filename, data_queue): with open(filename, "w") as f: while True: data = data_queue.get() if data == "STOP": break f.write(data + "\n") # 读取数据从文件的进程 def read_data(filename, data_queue): with open(filename, "r") as f: for line in f: data_queue.put(line.strip()) if __name__ == "__main__": # 创建一个进程共享队列 data_queue = multiprocessing.Queue() # 创建写入文件的进程 write_process = multiprocessing.Process(target=write_data, args=("data.txt", data_queue)) # 创建读取文件的进程 read_process = multiprocessing.Process(target=read_data, args=("data.txt", data_queue)) # 启动进程 write_process.start() read_process.start() # 等待写入进程完成 write_process.join() # 停止读取进程 data_queue.put("STOP") ``` 在这个例子中,我们创建了一个共享队列 `data_queue`,写入进程将数据写入这个队列,读取进程从这个队列中读取数据。 需要注意的是,在写入进程中,我们需要将数据写入文件中并且添加一个换行符,而在读取进程中,我们需要使用 `strip()` 方法来去掉读取的每一行数据的换行符。此外,在写入进程完成后,我们向队列中添加一个 `STOP` 标记来停止读取进程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值