简体   繁体   English

将行写入不同的文件

[英]Writing Lines to a Different File

I am reading content from a file (scores.txt) and I have formatted the data that I need from it and I would like to write those lines to a new file. 我正在从文件(scores.txt)中读取内容,并且已经从文件中格式化了所需的数据,我想将这些行写入新文件中。 The new file I will be writing to is top_scores.txt. 我将要写入的新文件是top_scores.txt。 Below is the code for the desired output. 以下是所需输出的代码。 I am just not entirely sure how to print to the file. 我只是不完全确定如何打印到文件。

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))

Sample from scores.txt: 来自scores.txt的示例:

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

Sample for desired input for new file: 新文件所需输入的样本:

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

"(...) the variables I have defined to hold the data I need, are not defined (...)" “(...)我为保存所需数据而定义的变量未定义(...)”

Maybe that's caused by lines like these: 可能是由以下几行引起的:

for i in studentScores:
    float(i)

float(i) doesn't convert the value of i in a "lasting" way unless you assign a variable to it; float(i)不会以“持久”的方式转换i的值,除非您为其分配了变量。 eg do score = float(i) or whatever you want to call it. 例如, score = float(i)或任何您想调用的名称。 You can then work with score which is now a floating point number. 然后,您可以使用score ,现在是浮点数。

When writing to files, like in the line below, you have to write a single string at a time. 写入文件时(如下面的行所示),您必须一次写入一个字符串。 When you place a comma between the values, they won't be combined into a single string so python will most likely fail with a TypeError: function takes exactly 1 argument (x given) . 当您在值之间放置逗号时,它们将不会合并为单个字符串,因此python很可能会因TypeError: function takes exactly 1 argument (x given)失败TypeError: function takes exactly 1 argument (x given)

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

If studentNames and studentsList are list s and int(topScore) is an integer, none of the variables can be written to a file as is. 如果studentNamesstudentsListlist并且int(topScore)是整数,则任何变量都不能int(topScore)写入文件。 You will need to select individual strings from your list s (eg studentNames[0] ) or use " ".join(name_of_your_list) to combine all elements into a single string. 您需要从list选择单个字符串(例如, studentNames[0] ),或使用" ".join(name_of_your_list)将所有元素组合为一个字符串。 int(topScore) will have to be converted to a string via str(topScore) . int(topScore)必须通过str(topScore)转换为字符串。

"I am just not entirely sure how to print to the file." “我只是不太确定如何打印到文件。”

The easiest way to handle file reading/writing is via with open(filename, mode) handle: . 处理文件读/写的最简单方法是with open(filename, mode) handle: Eg: 例如:

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

Just some observations that'll explain at least some of the errors you're probably getting... 只是一些观察结果至少可以解释您可能会遇到的一些错误...

To write to a file just use : 要写入文件,只需使用:

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

Here is a correct way to achieve what you want : 这是实现所需目标的正确方法:

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

Note that I used two ways to print the result : 请注意,我使用两种方法来打印结果:

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

Also note that I used a with statement like jDo suggested. 另外请注意,我使用了一个with语句,如jDo建议。

This way, it permits to open a file and to automatically close it when exiting the block. 这样,它允许打开文件并在退出块时自动关闭文件。

EDIT : 编辑:

Here is a version that is even shorter : 这是一个更短的版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM