删除从文件中读取的列表中的换行符

时间:2010-11-30 22:14:12

标签: python list newline

我有一个简单的程序,它带有一个ID号,并为匹配该ID的人打印信息。信息存储在.dat文件中,每行一个ID号。

问题是我的程序还在从文件中读取换行符\ n。我尝试了'name'.split()方法,但这似乎不适用于列表。

我的节目:

from time import localtime, strftime

files = open("grades.dat")
request = open("requests.dat", "w")
lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))

cont = "y"

while cont == "y" or cont == "Y":
    answer = raw_input("Please enter the Student I.D. of whom you are looking: ")
    for i in range(len(grades)):
        if answer == grades[i][0]:
            print grades[i][1] + ", " + grades[i][2] + (" "*6) + grades[i][0] + (" "*6) + grades[i][3]
            time = strftime("%a, %b %d %Y %H:%M:%S", localtime())
            print time
            print "Exams - " + grades[i][11] + ", " + grades[i][12] + ", " + grades[i][13]
            print "Homework - " + grades[i][4] + ", " + grades[i][5] + ", " + grades[i][6] + ", " + grades[i][7] + ", " +grades[i][8] + ", " + grades[i][9] + ", " + grades[i][10]
            total = int(grades[i][4]) + int(grades[i][5]) + int(grades[i][6]) + int(grades[i][7]) + int(grades[i][8]) + int(grades[i][9]) + int(grades[i][10]) + int(grades[i][11]) + int(grades[i][12]) + int(grades[i][13])
            print "Total points earned - " + str(total)
            grade = float(total) / 550
            grade = grade * 100
            if grade >= 90:
                print "Grade: " + str(grade) + ", that is equal to an A."
            elif grade >= 80 and grade < 90:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to a B."
            elif grade >= 70 and grade < 80:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to a C."
            elif grade >= 60 and grade < 70:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to a D."
            else:
                print "Grade: " + str('%.2f' %grade) + ", that is equal to an F."
            request.write(grades[i][0] + " " + grades[i][1] + ", " + grades [i][2] +
                          " " + time)
            request.write("\n")


    print
    cont = raw_input("Would you like to search again? ")

if cont != "y" or cont != "Y":
    print "Goodbye."

5 个答案:

答案 0 :(得分:75)

str.strip()返回一个字符串,其中删除了前导+尾部空格,.lstrip.rstrip仅分别用于前导和尾随。

grades.append(lists[i].rstrip('\n').split(','))

答案 1 :(得分:18)

您可以使用strip()函数删除尾随(和前导)空格;传递一个参数将允许您指定哪个空格:

for i in range(len(lists)):
    grades.append(lists[i].strip('\n'))

看起来您可以简化整个块,因为如果您的文件每行存储一个ID grades只有lists,并且新行已被删除:

之前

lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))

grades = [x.strip() for x in files.readlines()]

(以上是list comprehension


最后,您可以直接遍历列表,而不是使用索引:

之前

for i in range(len(grades)):
    # do something with grades[i]

for thisGrade in grades:
    # do something with thisGrade

答案 2 :(得分:4)

你可以通过将整个文件作为单个长字符串读入内存然后使用它们将其拆分为成绩列表来实际使用新行。

with open("grades.dat") as input:
    grades = [line.split(",") for line in input.read().splitlines()]
etc...

答案 3 :(得分:2)

以下是适当的Python风格的各种优化和应用程序,以使您的代码更整洁。我使用csv模块添加了一些可选代码,这比手动解析更合适。我也有点namedtuple善良,但我不使用当时提供的属性。 namedtuple部分的名称不准确,您需要更正它们。

import csv
from collections import namedtuple
from time import localtime, strftime

# Method one, reading the file into lists manually (less desirable)
with open('grades.dat') as files:
    grades = [[e.strip() for e in s.split(',')] for s in files]

# Method two, using csv and namedtuple
StudentRecord = namedtuple('StudentRecord', 'id, lastname, firstname, something, homework1, homework2, homework3, homework4, homework5, homework6, homework7, exam1, exam2, exam3')
grades = map(StudentRecord._make, csv.reader(open('grades.dat')))
# Now you could have student.id, student.lastname, etc.
# Skipping the namedtuple, you could do grades = map(tuple, csv.reader(open('grades.dat')))

request = open('requests.dat', 'w')
cont = 'y'

while cont.lower() == 'y':
    answer = raw_input('Please enter the Student I.D. of whom you are looking: ')
    for student in grades:
        if answer == student[0]:
            print '%s, %s      %s      %s' % (student[1], student[2], student[0], student[3])
            time = strftime('%a, %b %d %Y %H:%M:%S', localtime())
            print time
            print 'Exams - %s, %s, %s' % student[11:14]
            print 'Homework - %s, %s, %s, %s, %s, %s, %s' % student[4:11]
            total = sum(int(x) for x in student[4:14])
            print 'Total points earned - %d' % total
            grade = total / 5.5
            if grade >= 90:
                letter = 'an A'
            elif grade >= 80:
                letter = 'a B'
            elif grade >= 70:
                letter = 'a C'
            elif grade >= 60:
                letter = 'a D'
            else:
                letter = 'an F'

            if letter = 'an A':
                print 'Grade: %s, that is equal to %s.' % (grade, letter)
            else:
                print 'Grade: %.2f, that is equal to %s.' % (grade, letter)

            request.write('%s %s, %s %s\n' % (student[0], student[1], student[2], time))


    print
    cont = raw_input('Would you like to search again? ')

print 'Goodbye.'

答案 4 :(得分:0)

你想要String.strip(s [,chars])函数,它会去掉你在chars参数中指定的空格字符或任何字符(例如'\ n')。

请参阅http://docs.python.org/release/2.3/lib/module-string.html