将行写入不同的文件

Writing Lines to a Different File

我正在从一个文件 (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], max score = 95\n

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

可能是这样的行造成的:

for i in studentScores:
    float(i)

float(i) 不会以 "lasting" 的方式转换 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)是一个整数,none的变量可以原样写入文件.您将需要 select 来自 list 的单个字符串(例如 studentNames[0])或使用 " ".join(name_of_your_list) 将所有元素组合成一个字符串。 int(topScore) 必须通过 str(topScore) 转换为字符串。

"I am just not entirely sure how to print to the file."

处理文件 reading/writing 的最简单方法是通过 with open(filename, mode) handle:。例如:

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

只是一些观察结果,至少可以解释 一些 您可能遇到的错误...

要写入文件只需使用:

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

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

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() 方法。

另请注意,我使用了 jDo 建议的 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")