如何在Python中保存文件的缩进格式

时间:2020-12-27 16:57:26

I am saving all the words from a file like so:

我正在保存文件中的所有单词,如下所示:

     sentence = " "
   fileName = sys.argv[1]
   fileIn = open(sys.argv[1],"r")
   for line in open(sys.argv[1]):
      for word in line.split(" "):
         sentence += word

Everything works okay when outputting it except the formatting. I am moving source code, is there any way I can save the indention?

除格式化外,输出时一切正常。我正在移动源代码,有什么办法可以保存缩进吗?

3 个解决方案

#1


When you invoke line.split(), you remove all leading spaces.

调用line.split()时,将删除所有前导空格。

What's wrong with just reading the file into a single string?

将文件读入单个字符串有什么问题?

textWithIndentation = open(sys.argv[1], "r").read()

#2


Since you state, that you want to move source code files, why not just copy/move them?

既然你说要移动源代码文件,为什么不复制/移动它们呢?

import shutil
shutil.move(src, dest)

If you read source file,

如果您阅读源文件,

fh = open("yourfilename", "r")
content = fh.read()

should load your file as it is (with indention), or not?

应该按原样(带缩进)加载文件吗?

#3


Split removes all spaces:

拆分删除所有空格:

>>> a="   a b   c"
>>> a.split(" ")
['', '', '', 'a', 'b', '', '', 'c']

As you can see, the resulting array doesn't contain any spaces anymore. But you can see these strange empty strings (''). They denote that there has been a space. To revert the effect of split, use join(" "):

如您所见,生成的数组不再包含任何空格。但你可以看到这些奇怪的空字符串('')。他们表示有空间。要恢复拆分的效果,请使用join(“”):

>>> l=a.split(" ")
>>> " ".join(l)
'   a b   c'

or in your code:

或者在你的代码中:

sentence += " " + word

Or you can use a regular expression to get all spaces at the start of the line:

或者,您可以使用正则表达式来获取行开头的所有空格:

>>> import re
>>> re.match(r'^\s*', "   a b   c").group(0)
'   '

#1


When you invoke line.split(), you remove all leading spaces.

调用line.split()时,将删除所有前导空格。

What's wrong with just reading the file into a single string?

将文件读入单个字符串有什么问题?

textWithIndentation = open(sys.argv[1], "r").read()

#2


Since you state, that you want to move source code files, why not just copy/move them?

既然你说要移动源代码文件,为什么不复制/移动它们呢?

import shutil
shutil.move(src, dest)

If you read source file,

如果您阅读源文件,

fh = open("yourfilename", "r")
content = fh.read()

should load your file as it is (with indention), or not?

应该按原样(带缩进)加载文件吗?

#3


Split removes all spaces:

拆分删除所有空格:

>>> a="   a b   c"
>>> a.split(" ")
['', '', '', 'a', 'b', '', '', 'c']

As you can see, the resulting array doesn't contain any spaces anymore. But you can see these strange empty strings (''). They denote that there has been a space. To revert the effect of split, use join(" "):

如您所见,生成的数组不再包含任何空格。但你可以看到这些奇怪的空字符串('')。他们表示有空间。要恢复拆分的效果,请使用join(“”):

>>> l=a.split(" ")
>>> " ".join(l)
'   a b   c'

or in your code:

或者在你的代码中:

sentence += " " + word

Or you can use a regular expression to get all spaces at the start of the line:

或者,您可以使用正则表达式来获取行开头的所有空格:

>>> import re
>>> re.match(r'^\s*', "   a b   c").group(0)
'   '