如何用多个 .txt 文件中的其他内容替换行的特定第一个字符? (Python)

How do I replace the a specific first character of lines with something else in multiple .txt files? (Python)

基本上我有这种形式的 .txt 文件

0 45 56 67 89
1 45 56 33 21
    

一些 .txt 文件也可能是空白的。有些可能包含一行或多行。现在我想将行的第一个字符中的所有 1 替换为 0。其他一切都保持不变。所以上面的 .txt 示例应该看起来像

0 45 56 67 89
0 45 56 33 21

我尝试了两种方法一种方法是:

import glob
import os
source="path of my folder/"
for filename in glob.glob(os.path.join(source, '*.txt')):
    with open(os.path.join(os.getcwd(), filename), "r+") as f:
        lines = f.readlines()
for filename in glob.glob(os.path.join(source, '*.txt')):
    with open(os.path.join(os.getcwd(), filename), "w+") as f:
        for line in lines:
            if line[0]=='1':
                line[0].replace('1','0')

但这只会删除所有行,无论它是以 0 还是 1 开头

我试过这个:

source="path/ of my folder which has the files/"
for root, dirs, filenames in os.walk(source):
    for f in filenames:
        this_file = open(os.path.join(source, f), "r")
        this_files_data = this_file.readlines()
        this_file.close()
# rewrite the file with all line except the one you don't want
        this_file = open(os.path.join(source, f), "w")
        for line in this_files_data:
            if line[0] in "1":
                line[0].replace("0","1")
                this_file.write(line)
        this_file.close()

但这只会删除所有以 0 开头的行,并保留以 1 开头的行。

您应该只使用一个循环。阅读每个文件,进行所需的更改,然后重写文件。

您可以使用正则表达式替换每行开头的 1

import re
import glob
import os

for filename in glob.glob(os.path.join(source, '*.txt')):
    with open(filename, "r") as f:
        contents = f.read()
    contents = re.sub(r'^1', '0', contents, flags = re.MULTILINE)
    with open(filename, "w") as f:
        f.write(contents)

你不应该使用 os.path.join(getcwd(), filename)。这些文件位于 source 目录中,而不是当前目录中,并且 glob.glob() returns 这些路径名。