【问题标题】:Strip leading and trailing spaces on 851 files in Python在 Python 中去除 851 个文件的前导和尾随空格
【发布时间】:2020-04-05 19:00:17
【问题描述】:

我想从我的 851 文件中去除前导和尾随空格。我怎样才能做到这一点?第一个文件由 220 行组成。最后一个文件由 1315 行组成。 我试过了:

x = 1
while x < 852:
    f = open("final.%d.txt" % x)
    lines = f.readlines()
    for i in range(0,row+1):
        str_a = lines[i]
        print(str_a.strip())
    x = x + 1

但它只输出 851 个文件名。

【问题讨论】:

  • 这段代码中的row是什么?

标签: python-3.x for-loop while-loop strip


【解决方案1】:

我不完全确定你想做什么,但我会假设:

  • 你要读取的内容有851个文件名为final.1.txt、final.2.txt、final.3.txt等
  • 对于这些文件中的每一个,您都希望去除该文件中每一行的所有尾随和前导空格
  • 您想将其保存在一个新文件中。

我现在将为您提供一个解决方案,将没有空格的文件写入另一个目录。这样,如果这不是您想要的,您就不会覆盖您的输入文件。如果我的假设是错误的,您能否更准确地说明您想要做什么?

import os, os.path

output_directory = "files_stripped"
os.makedirs(output_directory, exist_ok=True)

for x in range(1, 852):
    input_file_name = f"final.{x}.txt"
    output_file_name = os.path.join(output_directory, f"final.{x}.txt")
    with open(input_file_name) as input_file:
        with open(output_file_name, "w") as output_file:
            for input_line in input_file:
                output_line = input_line.strip()
                output_file.write(output_line + "\n")

【讨论】:

  • 非常感谢。
猜你喜欢
  • 2019-12-16
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多