【问题标题】:Replace text in file to new file in for loop with open用 open 将文件中的文本替换为 for 循环中的新文件
【发布时间】:2022-01-29 20:59:53
【问题描述】:

我正在研究一个关于 python 可理解性的难题,我目前正在尝试打开一个文件,读取它,替换一些文本,然后将替换的文本写入一个已创建和指定的新文件。现在,作为我解决这个难题的一部分,我正在清理日期时间查找字符串并尝试重新排列它并更改信息,以便以后更容易组织它。我遇到的问题是,当我尝试替换文本时它不起作用,只打印以工作日信息开头的过滤日期。
我很确定这是因为它试图在我指定为只读的文件上写入,但是当我用 outfile.replace 或 oline.replace 替换 'fline.replace(...) 时,它用 pycharm 告诉我.replace 不能在 outfline 和 oline 所在的类中调用。所以我对如何调用正确的文件/变量来执行.replace有点困惑。如果我使用this longer method,我可以让它工作,但我试图让它与“with open”和一个 for 循环一起工作,以建立我的 for 循环基础。我还尝试将 with open(...) as outfile: 包含在具有相同问题的 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 月 8 日 22:52:57
2018-04-03T05:18:28.737971
2023 年 12 月 21 日星期四 11:35:04
2019-09-25T22:54:08.456561
2025 年 4 月 19 日星期六 01:49:18
2020 06 04 10:06:01
2021 年 2 月 3 日下午 02:47:55
2024-01-27T08:48:32.559333
2014 年 5 月 21 日下午 05:31:48
2014 年 7 月 23 日上午 12:07:21
2026 年 5 月 11 日星期一 05:41:27

我一直 looking at other questions 与此类似,我觉得有一些方法可以更优雅地使用其他涉及的模块,并且 .replace 有更多问题,但正如我一样对 python 非常陌生,我无法理解其他模块方法。我想了解这里出了什么问题。我正在寻找有关为什么我所做的事情不起作用以及如何解决它的信息,以便我了解未来的问题。提前致谢。

【问题讨论】:

    标签: python for-loop replace


    【解决方案1】:

    我正在对您尝试解决的问题的性质做出一些假设,如果我有错误,请纠正我。

    假设您想用任何内容替换 "DDD, " 的所有实例(注意多余的空格),
    您可能想通过添加额外的空格来搜索稍微修改的字符串...稍后再详细介绍。

    在下面的 sn-p 中,我添加了一些内联 cmets 以确认我的理解或澄清可能出现的问题。最后是一个建议。

    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)
    

    【讨论】:

    • 这样就解决了问题!如果其他人读到这个线程,我有一个小问题,它只过滤掉一个数据而不是很多数据,我只需要进一步缩进outfile.write(fline)!谢谢:)
    【解决方案2】:

    你能用这个修改检查你的代码吗?

    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)
    

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 2019-03-20
      • 1970-01-01
      • 2021-07-28
      • 2014-07-11
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 2018-06-01
      相关资源
      最近更新 更多