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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4319236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:14:06  来源:igfitidea点击:

Remove the newline character in a list read from a file

pythonlistnewline

提问by Python Newbie

I have a simple program that takes an ID number and prints information for the person matching the ID. The information is stored in a .dat file, with one ID number per line.

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

The problem is that my program is also reading the newline character \n from the file. I have tried the 'name'.split() method, but this doesn't seem to work for a list.

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

My program:

我的程序:

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."

采纳答案by ephemient

str.strip()returns a string with leading+trailing whitespace removed, .lstripand .rstripfor only leading and trailing respectively.

str.strip()返回一个去除了前导+尾随空格的字符串,.lstrip并且.rstrip分别只用于前导和尾随。

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

回答by Michael Mrozek

You can use the strip()function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:

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

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


It looks like you can just simplify the whole block though, since if your file stores one ID per line gradesis just listswith newlines stripped:

看起来你可以简化整个块,因为如果你的文件每行存储一个 IDgrades只是lists去掉换行符:

Before

lists = files.readlines()
grades = []

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

After

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

(the above is a list comprehension)

(以上是列表理解



Finally, you can loop over a list directly, instead of using an index:

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

Before

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

After

for thisGrade in grades:
    # do something with thisGrade

回答by DGH

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

您需要 String.strip(s[, chars]) 函数,它将去除空白字符或您在 chars 参数中指定的任何字符(例如 '\n')。

See http://docs.python.org/release/2.3/lib/module-string.html

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

回答by Chris Morgan

Here are various optimisations and applications of proper Python style to make your code a lot neater. I've put in some optional code using the csvmodule, which is more desirable than parsing it manually. I've also put in a bit of namedtuplegoodness, but I don't use the attributes that then provides. Names of the parts of the namedtuple are inaccurate, you'll need to correct them.

这里有适当的 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.'

回答by martineau

You could actually put the newlines to good use by reading the entire file into memory as a single long string and then use them to split that into the list of grades.

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

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