假设我有一个包含以下内容的文件:
假设<tab>
实际上是一个选项卡和 <space>
实际上是一个空间。 (忽略引号)
"
<tab><tab>
<space>
<tab>
The clothes at
the superstore are
at a discount today.
"
假设这是一个文本文件。如何删除所有空格以使生成的文本文件为(忽略引号:
"
The clothes at
the superstore are
at a discount today.
"
最佳答案
假设您不想覆盖旧文件,请尝试此操作。如果您这样做,很容易适应:
oldfile = open("EXISTINGFILENAME", "r")
data = oldfile.read()
oldfile.close()
stripped_data = data.lstrip()
newfile = open("NEWFILENAME", "w")
newfile.write(stripped_data)
newfile.close()
请注意,这只会删除前导空格,要删除所有尾随空格,请使用 strip
代替 lstrip
。
关于python - 如何删除所有空格和换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16714903/