在python中加载文件

Jac*_*don 0 python load newline

我在使用以下代码时遇到了一些问题:

with open('townhall.map', 'r') as f:
    for line in f: 
        for character in line:
            if character == "x":
                print "WALL"
            else:
                if character == "a":
                    print "LAND"
                else:
                    print "Unexpected Error loading map!"
Run Code Online (Sandbox Code Playgroud)

townhall.map:

xxxxx
xaaax
xaaax
xaaax
xxxxx
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是它将换行符读为字符; 所以我得到了输出 -

WALL
WALL
WALL
WALL
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
LAND
LAND
LAND
WALL
Unexpected Error loading map!
WALL
WALL
WALL
WALL
WALL
Run Code Online (Sandbox Code Playgroud)

如何让它忽略换行符'字符'?

eum*_*iro 5

改变这一行:

for character in line.rstrip():
Run Code Online (Sandbox Code Playgroud)

你也可以使if/else结构更平坦:

with open('townhall.map', 'r') as f:
    for line in f: 
        for character in line.rstrip():
            if character == "x":
                print "WALL"
            elif character == "a":
                print "LAND"
            else:
                print "Unexpected Error loading map!"
Run Code Online (Sandbox Code Playgroud)

或者将打印定义为字典:

char = {'x': 'WALL',
        'a': 'LAND'}
with open('townhall.map', 'r') as f:
    for line in f: 
        for character in line.rstrip():
            try:
                print char[character]
            except KeyError:
                print "Unexpected Error loading map!"
Run Code Online (Sandbox Code Playgroud)