简体   繁体   English

从一个文件写入另一个文件

[英]Writing from one file to another

I've been stuck on this Python homework problem for awhile now: "Write a complete python program that reads 20 real numbers from a file inner.txt and outputs them in sorted order to a file outter.txt." 我已经在这个Python作业问题上停留了一段时间了:“编写一个完整的python程序,该程序从文件inner.txt中读取20个实数并将它们按排序顺序输出到文件outter.txt中。”

Alright, so what I do is: 好吧,所以我要做的是:

f=open('inner.txt','r')
n=f.readlines()
n.replace('\n',' ')
n.sort()
x=open('outter.txt','w')
x.write(print(n))

So my thought process is: Open the text file, n is the list of read lines in it, I replace all the newline prompts in it so it can be properly sorted, then I open the text file I want to write to and print the list to it. 所以我的想法是:打开文本文件,n是其中的读取行的列表,我替换了其中的所有换行符提示,以便可以对其进行正确排序,然后打开要写入的文本文件并打印列出来。 First problem is it won't let me replace the new line functions, and the second problem is I can't write a list to a file. 第一个问题是它不允许我替换新的换行函数,第二个问题是我不能将列表写入文件。

I just tried this: 我只是试过这个:

>>> x= "34\n"
>>> print(int(x))
34

So, you shouldn't have to filter out the "\\n" like that, but can just put it into int() to convert it into an integer. 因此,您不必像这样过滤掉"\\n" ,而只需将其放入int()即可将其转换为整数。 This is assuming you have one number per line and they're all integers. 假设每行有一个数字,它们都是整数。

You then need to store each value into a list. 然后,您需要将每个值存储到列表中。 A list has a .sort() method you can use to then sort the list. 列表具有.sort()方法,您可以使用该方法对列表进行排序。

EDIT: forgot to mention, as other have already said, you need to iterate over the values in n as it's a list, not a single item. 编辑:忘记提及,正如其他人已经说过的那样,您需要遍历n的值,因为它是一个列表,而不是单个项目。

Here's a step by step solution that fixes the issues you have :) 这是解决您遇到的问题的分步解决方案:)

Opening the file, nothing wrong here. 打开文件,这里没有错。

f=open('inner.txt','r')

Don't forget to close the file: 不要忘记关闭文件:

f.close()

n is now a list of each line: n现在是每行的列表:

n=f.readlines()

There are no list.replace methods, so I suggest changing the above line to n = f.read() . 没有list.replace方法,因此建议将上述行更改为n = f.read() Then, this will work (don't forget to reassign n , as strings are immutable): 然后,这将起作用(不要忘记重新分配n ,因为字符串是不可变的):

n = n.replace('\n','')

You still only have a string full of numbers. 您仍然只有一个充满数字的字符串。 However, instead of replacing the newline character, I suggest splitting the string using the newline as a delimiter: 但是,我建议不要使用换行符来分隔字符串,而是替换换行符:

n = n.split('\\n')

Then, convert these strings to integers: 然后,将这些字符串转换为整数:

`n = [int(x) for x in n]`

Now, these two will work: 现在,这两个将起作用:

n.sort()
x=open('outter.txt','w')

You want to write the numbers themselves, so use this: 您想自己写数字,所以使用这个:

x.write('\n'.join(str(i) for i in n))

Finally, close the file: 最后,关闭文件:

x.close()

Using a context manager (the with statement) is good practice as well, when handling files: 在处理文件时,使用上下文管理器( with语句)也是一种好习惯:

with open('inner.txt', 'r') as f:
    # do stuff with f
# automatically closed at the end

I guess real means float. 我想real意思是浮动。 So you have to convert your results to float to sort properly. 因此,您必须将结果转换为float才能正确排序。

raw_lines = f.readlines()
floats = map(float, raw_lines)

Then you have to sort it. 然后,您必须对其进行排序。 To write result back, you have to convert to string and join with line endings: 要写回结果,您必须转换为字符串并以行尾连接:

sortеd_as_string = map(str, sorted_floats)
result = '\n'.join(sortеd_as_string)

Finally you have have to write result to destination. 最后,您必须将结果写入目的地。

Ok let's look it step by step what you want to do. 好吧,让我们逐步看一下您想要做什么。

First: Read some integers out of a textfile. 第一:从文本文件中读取一些整数。

Pythonic Version: Pythonic版本:

fileNumbers = [int(line) for line in open(r'inner.txt', 'r').readlines()]

Easy to get version: 易于获取的版本:

fileNumbers = list()
with open(r'inner.txt', 'r') as fh:
    for singleLine in fh.readlines():
        fileNumbers.append(int(singleLine))

What it does: 它能做什么:

  1. Open the file 开启档案
  2. Read each line, convert it to int (because readlines return string values) and append it to the list fileNumbers 读取每一行,将其转换为int(因为readlines返回字符串值),并将其附加到列表fileNumbers

Second: Sort the list 第二:对列表进行排序

fileNumbers.sort()

What it does: 它能做什么:
The sort function sorts the list by it's value eg [5,3,2,4,1] -> [1,2,3,4,5] sort功能按列表的值对列表进行排序,例如[5,3,2,4,1] -> [1,2,3,4,5]

Third: Write it to a new textfile 第三:将其写入新的文本文件

with open(r'outter.txt', 'a') as fh:
    [fh.write('{0}\n'.format(str(entry))) for entry in fileNumbers]

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

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