Skip to main content
 首页 » 编程设计

python 2.6.6 "phantom"空格

2025年05月04日7zlslch

基本上,我打开一些文件并从该文件的每一行中删除所有空格。 代码片段:

for filepath in filelist: 
        if filepath.endswith(".shader"): 
            shaderfile = open(filepath,"r").readlines() 
            for line in shaderfile: 
                line = Left(line, line.find("\n"))+"\n" 
                line = line.replace(" ","") 
                if line.find("common/")>-1: 
                    print(line.replace("\n","\\n")) 

根据要求,我删除了不太重要的代码。

发生了两件奇怪的事情:

1) 部分行以“\n\n”结尾

2) 我得到这个输出:

textures/common/lightgrid\n 
textures/common/mirror1 
 \n 
textures/common/mirror2 
 \n 
maptextures/common/invisible.tga 
 \n 
textures/common/watercaulk 
 \n 
textures/common/clipnokick 
 \n 
textures/common/invisible\n 

3) 当我在这里粘贴输出时,它看起来像:

textures/common/lightgrid\n 
textures/common/mirror1\n 
textures/common/mirror2\n 
maptextures/common/invisible.tga\n 
textures/common/watercaulk\n 
textures/common/clipnokick\n 
textures/common/invisible\n 

我真的不知道发生了什么。是 print() 的错误吗? 抱歉格式错误,但这不是我的错,而是 stackoverflow 的错。

请您参考如下方法:

from StringIO import StringIO 
 
a = StringIO("""textures/common/lightgrid 
textures/common/mirror1 
 
textures/common/mirror2 
 
maptextures/common/invisible.tga 
 
textures/common/watercaulk 
 
textures/common/clipnokick 
 
textures/common/invisible""") 
 
 
def clean_lines(fileobj): 
    for line in fileobj: 
        if line: 
            line = line.strip() 
            if line: 
                yield "%s\n" % line 
 
 
print [line for line in clean_lines(a)] 

我使用 stringIO 来模拟一个文件,只需将 a 替换为您的 fileobj 即可。