将行写入不同的文件

时间:2016-04-19 01:55:54

标签: python file-writing

我正在从文件(scores.txt)中读取内容,并且我已经格式化了我需要的数据,并且我想将这些行写入新文件。我将写的新文件是top_scores.txt。下面是所需输出的代码。我只是不完全确定如何打印到文件。

infile = open('scores.txt', 'r')
lineList = sorted(infile.readlines())

for lines in lineList:
    newLine = lines.replace('\n', '')
    splitLines = newLine.split(',')
    studentNames = splitLines[0]
    studentScores = splitLines[1:]
    studentsList = []
    for i in studentScores:
        studentsList.append(int(i))
    topScore = max(studentsList)
    print(studentNames.capitalize() + ': ', studentsList, 'max score =', int(topScore))

来自scores.txt的样本:

  

PMAS,95,72,77,84,86,81,74,\ n

新文件所需输入的示例:

  

Pmas:[95,72,77,84,86,81,74],最高分= 95 \ n

3 个答案:

答案 0 :(得分:0)

“(...)我定义的变量用于保存我需要的数据,未定义(...)”

也许这是由以下几行造成的:

for i in studentScores:
    float(i)

float(i)除非您为其指定变量,否则不会以“持久”方式转换i的值;例如做score = float(i)或你想要的任何东西。然后,您可以使用score,它现在是一个浮点数。

写入文件时,如下面的行,您必须一次写一个字符串。当您在值之间放置逗号时,它们不会合并为单个字符串,因此python很可能会失败并显示TypeError: function takes exactly 1 argument (x given)

infile2.write(studentNames.capitalize() + ': ', studentsList, 'top score =', int(topScore))

如果studentNamesstudentsListlistint(topScore)为整数,则不能将任何变量按原样写入文件。您需要从list中选择单个字符串(例如studentNames[0])或使用" ".join(name_of_your_list)将所有元素组合成单个字符串。 int(topScore)必须通过str(topScore)转换为字符串。

“我只是不完全确定如何打印到文件。”

处理文件读/写的最简单方法是通过with open(filename, mode) handle:。 E.g:

with open("output_file.txt", "w") as f:
    f.write(some_string)

只是一些观察,至少可以解释某些你可能会得到的错误......

答案 1 :(得分:0)

要写入文件,只需使用:

file = open("top_score.txt", "a")
str=', '.join(str(x) for x in studentsList)
file.write(studentNames.capitalize() +'\t'+str+'\t'+(topScore))
file.close();

答案 2 :(得分:0)

这是实现目标的正确方法:

with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", '\
w') as outfile2:
    lineList = sorted(infile.readlines())
    for lines in lineList:
        newLine = lines.replace('\n', '')
        splitLines = newLine.split(',')
        studentNames = splitLines[0]
        studentScores = splitLines[1:]
        studentsList = []
        for i in studentScores:
            if i == '':
                break
            studentsList.append(int(i))
        topScore = max(studentsList)
        result = "%s: %s,max score = %d" % (studentNames.capitalize(),
                                            str(studentsList),
                                            max(studentsList))
        print(result)
        print(result, file = outfile)
        outfile2.write(result + "\n")

请注意,我使用两种方法打印结果:

  • print()文件参数。
  • file.write()方法。

另请注意,我使用了j {建议的with语句。

这样,它允许打开文件并在退出块时自动关闭它。

编辑:

这是一个更短的版本:

with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", 'w') as outfile2:
    lineList = sorted(infile.readlines())
    for lines in lineList:
        lines = lines.replace('\n', '').split(',')
        studentScores = lines[1:-1]
        studentsList = [int(i) for i in studentScores]
        result = "%s: %s,max score = %d" % (lines[0].capitalize(),
                                            str(studentsList),
                                            max(studentsList))
        print(result)
        print(result, file = outfile)
        outfile2.write(result + "\n")