如何从我的python字典中删除\ n?

时间:2014-04-06 06:19:35

标签: python python-2.7 dictionary

所以我有一个类似的文本文件:

apples,green
tomatos,red
bananas,yellow

我将此作为字典使用的代码是

def load_list(filename):
    with open(filename, "rU") as my_file:
        my_list = {}
        for line in my_file:
            x = line.split(",")
            key = x[0]
            value = x[1]
            my_list[key] = value
        print my_list

工作正常,但由于换行符,每个值都添加到它的末尾。我尝试添加

.strip()

到x属性,但它在属性错误中被重新出现(AttributeError:' dict'对象没有属性' strip')。

那么如何删除\ n?

3 个答案:

答案 0 :(得分:10)

分割前你应该strip,像这样

x = line.rstrip("\n").split(",")

我们在这里使用str.rstrip,因为我们只需要删除行尾的换行符。

此外,您可以立即解压缩密钥和值,如此

key, value = line.rstrip("\n").split(",")

答案 1 :(得分:0)

以下是一个完整的示例,说明了如何正常使用条带:

def main():
# Open a file named football.txt.
infile = open('football.txt', 'r')

# Read three lines from the file.
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()

Strip the \n from each string.
line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
line3 = line3.rstrip('\n')

# Close the file.
infile.close()

# Print the data that was read into memory.
print(line1)
print(line2)
print(line3)

# Call the main function.
main()

假设您想要将内容读入列表并删除换行符。您可以执行以下操作:

# This program reads a file's contents into a list.

def main():
# Open a file for reading.
infile = open('football.txt', 'r')

# Read the contents of the file into a list.
football = infile.readlines()

# Close the file.
infile.close()

# Strip the \n from each element.
index = 0
while index < len(football):
football[index] = football[index].rstrip('\n')
index += 1

# Print the contents of the list.
print(football)

# Call the main function.
main()

第二个程序版本可以轻松地将列表替换为只有少量非常小的更改的字典。

答案 2 :(得分:0)

顺便说一句,如果您使用csv module,这是您可以避免的问题之一,因为它会为您删除行:

import csv

def load_list(filename):
    with open(filename, 'r') as f:
        reader = csv.reader(f, delimiter=',')
        my_dict = {k:v for k,v in reader}
    return my_dict

我还将变量的名称更改为my_dict,因为它不是列表。