使用打开将文件中的文本替换为 for 循环中的新文件

Replace text in file to new file in for loop with open

我正在研究一个 python 可理解性的谜题,我目前正在尝试打开一个文件,阅读它,替换一些文本,然后将替换的文本写入一个新文件并指定。现在,作为我解决这个难题的一部分,我正在清理看起来像日期时间的字符串并尝试重新排列它并更改信息以便以后更容易地组织它。我遇到的问题是,当我尝试替换文本时它不起作用,只打印以工作日信息开头的过滤日期。
我很确定这是因为它试图在我指定为只读的文件上写入但是当我用 outfile.replace 或 oline.replace 替换 'fline.replace(...)它告诉我 pycharm 不能在 outfline 和 oline 所在的 class 中调用 .replace。所以我对如何调用正确的 file/variable 来执行 .replace 有点困惑。如果我使用 this longer method 我可以让它工作,但我试图让它与“打开”和 for 循环一起工作,以建立我的 for 循环基础。我还尝试将 with open(...) as outflile: 包含在具有相同问题的 for 循环中。

inf = "/Users/dusti/Documents/datetime25.txt"  
outf = "/Users/dusti/Documents/datetime30.txt"  
weekday = ('Mon,', 'Tue,', 'Wed,', 'Thu,', 'Fri,', 'Sat,', 'Sun,')   

with open(inf, "r") as infile:  
 with open(outf, "w") as outfile:  
 oline = outfile.write()  
  for fline in infile:  
   if fline.startswith(weekday):  
    fline.replace("Mon,", " ")  
    fline.replace('Tue,', " ")  
    fline.replace('Wed,', " ")  
    fline.replace('Thu,', " ")  
    fline.replace('Fri,', " ")  
    fline.replace('Sat,', " ")  
    fline.replace('Sun,', " ")  
     print(type(fline),fline)  

这是我在“.datetiime25”中查看的一小段信息。每次我只是想在整理所有 1000 行信息之前完善正在发生的事情时,新文件都会被覆盖。

2013 02 08 22:52:57
2018-04-03T05:18:28.737971
Thu, 21 Dec 2023 11:35:04
2019-09-25T22:54:08.456561
Sat, 19 Apr 2025 01:49:18
2020 06 04 10:06:01
02/03/2021 02:47:55 PM
2024-01-27T08:48:32.559333
05/21/2014 05:31:48 PM
07/23/2014 12:07:21 AM
Mon, 11 May 2026 05:41:27

我已经 与这个类似,我觉得有一些方法可以更优雅地处理其他涉及的模块,并且 .replace 有更多问题,但因为我是新手to python 一直没能看懂其他模块 methods.I 想了解一下这里哪里出了问题。我正在寻找有关为什么我所做的不起作用以及如何解决它的信息,以便我可以了解未来的问题。提前致谢。

你能检查一下修改后的代码吗?

inf = "/Users/dusti/Documents/datetime25.txt"  
outf = "/Users/dusti/Documents/datetime30.txt"  
weekday = ('Mon,', 'Tue,', 'Wed,', 'Thu,', 'Fri,', 'Sat,', 'Sun,')   

with open(inf, "r") as infile:  
 with open(outf, "w") as outfile:  
 oline = outfile.write()  
  for fline in infile:  
   if fline.startswith(weekday):  
    fline = fline.replace("Mon,", " ")  
    fline = fline.replace('Tue,', " ")  
    fline = fline.replace('Wed,', " ")  
    fline = fline.replace('Thu,', " ")  
    fline = fline.replace('Fri,', " ")  
    fline = fline.replace('Sat,', " ")  
    fline = fline.replace('Sun,', " ")  
   print(type(fline),fline)

我正在对您要解决的问题的性质做出一些假设,如果我有什么不对请纠正我。

假设您想要替换 "DDD, " 的所有实例(注意额外的 space),
您可能希望通过添加额外的 space 来搜索稍微修改过的字符串...稍后会详细介绍。

在下面的代码片段中,我添加了一些内联评论以确认我的理解或澄清可能出现的问题。最后是推荐。

weekday = ('Mon,', 'Tue,', 'Wed,', 'Thu,', 'Fri,', 'Sat,', 'Sun,')   

with open(inf, "r") as infile:  
    with open(outf, "w") as outfile:  

        # If you intend to call the .write() method, it will need an argument
        # so that the function knows what to write.
        # At this point, we don't seem to have anything to write, yet.
        # I am presuming this next line is out of place.
        oline = outfile.write()  

        for fline in infile:  

            # weekday is a tuple. It has strings in it, but it is a tuple. 
            # As such the text in fline will never start with it.
            # I feel like you want to cycle through each weekday in weekdays
            # and if you find that weekday, you simply want to replace that
            # snippet of text, if it is found.
            # We will need a different approach, more on this later.

            if fline.startswith(weekday):  
            
            # It should be noted that .replace() does not do an "in place"
            # replacement. If we want to save the results of the replacement, 
            # we need to set a variable to point at the result. 
            # Options include either of the following:
            # fline = fline.replace("Mon,", " ") if you just want the new data
            # newline = fline.replace("Mon,", " ") if you want to keep fline
            # untouched for later reference    
                fline.replace("Mon,", " ")  
                fline.replace('Tue,', " ")  
                fline.replace('Wed,', " ")  
                fline.replace('Thu,', " ")  
                fline.replace('Fri,', " ")  
                fline.replace('Sat,', " ")  
                fline.replace('Sun,', " ")  
                print(type(fline),fline)

我们可能会这样重写代码。

同样,假设我了解您的最终目标:

inf = "/Users/dusti/Documents/datetime25.txt"  
outf = "/Users/dusti/Documents/datetime30.txt"  

# We could add a blank space after each string in weekdays AND 
# give it the variable name weekdays to better reflect that it is
# a sequence of individual weekdays.

weekdays = ('Mon, ', 'Tue, ', 'Wed, ', 'Thu, ', 'Fri, ', 'Sat, ', 'Sun, ')   

with open(inf, "r") as infile:  
    with open(outf, "w") as outfile:  
        for fline in infile:  

            # We could parse each weekday in weekdays
            for weekday in weekdays:
                
                # For each weekday in weekdays, we could then
                # do a replacement of that weekday, if it exists
                # I am presuming that we don't want extraneous blank spaces 
                # To prevent "Mon, 11 May 2026 05:41:27" from becoming:
                #            "  11 May 2026 05:41:27"
                # 
                # We use our tuple ("Mon, ", "Tue, "...) with the slightly
                # enhanced "space-included" strings AND then we replace the
                # term with an empty string will ensure that the value comes out
                # as this: "11 May 2026 05:41:27" with no extraneous spaces.
 
                fline = fline.replace(weekday, "") # NOTE the empty string (`""`)
                                                   # as a replacement value
            
            # NOTE: this line is outdented from the for loop, cause
            # we only want to write to the outfile when we have
            # finished checking against each weekday in weekdays and have a 
            # final result to write.
            outfile.write(fline)