【问题标题】:Is there a way to replace "~" symbol with "~\n" in a text file using python script [duplicate]有没有办法使用python脚本在文本文件中用“~\n”替换“~”符号[重复]
【发布时间】:2021-05-14 08:59:54
【问题描述】:

我在一个文件夹中有大量的文本文件。现在我需要用“~\n”替换“~”符号 使用 python 脚本从所有文本文件中提取

我知道这可以在记事本++中实现,我需要将“~”符号放在“查找内容”和“~\n”替换部分,我需要检查可用的扩展选项并单击全部替换。但我需要一个一个来做。

我使用“\n”只是为了将单行分成多行,“~”是我的分隔符

因此,如果有人给我一个 python 脚本来一次性对所有文件执行相同的操作,那就太好了。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

假设你有一个这样的目录:

.
├── doc1.txt
├── doc2.txt
├── doc3.txt
├── doc4.txt
└── main.py

现在,如果您想浏览所有文本文件并将所有“~”替换为“~\n”。 为此,将以下代码粘贴到 python 中

import os

directory = os.listdir()
for file in directory:
    if ".txt" in file:
        with open(file, "r") as temp_file:
            temp = temp_file.read()
            temp = temp.replace("~", "~\n")
        print(f"Replacing '~' with '~\\n' in [{file}]")
        print(f"Replaced example: {temp}")
        with open(file, "w") as opened_file:
            opened_file.write(temp)
    else:
        print(f"Skipped {file} [Not a text file]")

【讨论】:

    【解决方案2】:
    text = "hi ~ uo~ ~~"
    
    i = text.replace("~", "~\n")
    
    print(i)
    

    【讨论】:

      【解决方案3】:

      我已经找到了一种方法,这是我的完整代码

      import os
      
      from tkinter import Tk, filedialog
      root = Tk() # pointing root to Tk() to use it as Tk() in program.
      root.withdraw() # Hides small tkinter window.
      root.attributes('-topmost', True) # Opened windows will be active. above all windows despite of selection.
      cwd = filedialog.askdirectory() # Returns opened path as str
      
      path = os.path.join(cwd, "converted_file")
      
      try:
          os.stat(path)
      except:
          os.mkdir(path)
      
      for filename in os.listdir(cwd):
          if os.path.isfile(os.path.join(cwd, filename)):
              with open(os.path.join(path, filename), 'w') as f:
                  t = open(filename, 'r')
                  t_contents = t.read()
                  t_contents = t_contents.replace("~", "~\n")
                  f.write(t_contents)
                  print(filename)
          else:
              continue
      

      【讨论】:

        猜你喜欢
        • 2020-03-02
        • 2015-10-03
        • 2016-03-12
        • 1970-01-01
        • 2019-12-05
        • 1970-01-01
        • 2023-02-26
        • 2019-02-11
        • 1970-01-01
        相关资源
        最近更新 更多