简体   繁体   English

如何让Python读取多个txt文件

[英]How to make Python read multiple txt files


I need help with this Python Script我需要有关此 Python 脚本的帮助
I am a noob to Python, but I really need this to work我是 Python 的菜鸟,但我真的需要这个才能工作

I made a batch script for this project and it works great, BUT it's very slow it can take 30 minutes to edit all 200 + files我为这个项目制作了一个批处理脚本,效果很好,但是速度很慢,编辑所有 200 多个文件可能需要 30 分钟

This is what I have and this works great but I have over 200 txt files with different names and all located in different folders这就是我所拥有的,而且效果很好,但是我有超过 200 个不同名称的 txt 文件,它们都位于不同的文件夹中

f1 = open('(1).txt', 'r')
f2 = open('(1A).txt', 'w')
for line in f1:
    f2.write(line.replace('"aplid": 2147483648', '"aplid": -2147483648'))
f1.close()
f2.close()

What I need is for this to work like this, so I have 2 codes per txt file that needs to be edited if this is to much to ask help on then I'll just make 2 copies of the same script one for each code我需要的是让它像这样工作,所以我每个 txt 文件有 2 个代码需要编辑,如果这需要太多帮助,那么我只需为每个代码制作 2 个相同脚本的副本

I made a call sub reader with batch to run the python.py script but it runs slow when using the batch script, so it would be great to make this this script have it's own sub folder reader我用批处理调用子阅读器来运行 python.py 脚本,但是在使用批处理脚本时运行速度很慢,所以让这个脚本有它自己的子文件夹阅读器会很棒

import glob
import os

for f in glob.glob("*.txt"):
f1 = open('f', 'r')
f2 = open('f', 'w')
for line in f1:
    f2.write(line.replace('"aplid": 2147483648,', '"aplid": -2147483648,'))
    f2.write(line.replace('"orlid": 2147483648,', '"orlid": -2147483648,'))
f1.close()
f2.close()

If it can read and write to the same files that would be great如果它可以读取和写入相同的文件,那就太好了
I don't know if Python can read Folders and subfolders like batch dir /b /s /ad我不知道 Python 是否可以读取批处理dir /b /s /ad之类的文件夹和子文件夹

But my main interest is for this to read any txt file and save to the same txt file但我的主要兴趣是读取任何 txt 文件并保存到同一个 txt 文件

I'm sorry for bothering you'll, but I searched online and I can't find anything that helps with this and most of it I don't understand很抱歉打扰您,但是我在网上搜索并找不到任何对此有帮助的东西,而且大部分我不明白

I keep reading that using a path can help, but this script is going to be placed in several computers so using path is not best我一直在阅读,使用路径会有所帮助,但是此脚本将放置在多台计算机中,因此使用路径不是最好的

You can use os.walk to traverse through a directory tree:您可以使用os.walk遍历目录树:

import os

for root, dirs, files in os.walk('.'):
    for name in files:
        nmin = os.path.join(root,name)
        with open(nmin,"r") as fin:
            data = fin.read()
        data = data.replace('"aplid": 2147483648,', '"aplid": -2147483648,') \
                   .replace('"orlid": 2147483648,', '"orlid": -2147483648,')
        with open(nmin,"w") as fout:
            fout.write(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM