Python中的新行不起作用

时间:2017-05-18 23:26:00

标签: python

我必须从一个文件中读取并将其输入到按字母顺序排列的另一个文件。所以我做了条带然后排序()现在我不能因为某些原因把它带到新线可以请一些人指导我做错了什么。

      infile = open("unsorted_fruits.txt", "r")
      outfile=open("sorted_fruits.txt","w")



      for line in infile:
          fruit=infile.read().split() 
          fruits = sorted(fruit)
          timeflies = str(fruits)
          outfile.write(timeflies + '\n');
          print (timeflies )



      infile.close()
      outfile.close()

3 个答案:

答案 0 :(得分:1)

你做错了什么:在第一次迭代中你已经在infile infile.read()阅读了所有内容,但是在第二次迭代中,没有什么可读的。所以你应该在循环之前读取文件并遍历排序列表。

试试这个:

infile = open("unsorted_fruits.txt", "r")
outfile=open("sorted_fruits.txt","w")

fruit=infile.read().split() 
fruits = sorted(fruit)
for line in fruits:
    timeflies = str(line)
    outfile.write(timeflies)
    print (timeflies )
infile.close()
outfile.close()

注意:.split()在每个空格处分割,每个新行。因此,如果您的水果名称中有空格,分开。

您可以查看代码的这个改进版本:

with open("unsorted_fruits.txt", "r") as infile, 
        open("sorted_fruits.txt","w") as outfile:
    fruits = sorted(infile.readlines())
    outfile.writelines(fruits)

答案 1 :(得分:0)

您正在编写数组本身。这是一个有效的修改版本。

infile = open("unsorted_fruits.txt", "r")
outfile=open("sorted_fruits.txt","w")

fruit=infile.read().split()

fruits = sorted(fruit)
timeflies = str(fruits)
print (timeflies )

for fruit in fruits:
    outfile.write(fruit + '\n')

infile.close()
outfile.close()

答案 2 :(得分:0)

<强>分析:

这是你的循环所做的,逐行:

# Reading each line of input:
for line in infile:

    # Ignore that first line and read
    #   the rest of the file.
    #   Split that into individual fruit names
    fruit=infile.read().split()

    # Sort the list of fruits #2 through end-of-file
    fruits = sorted(fruit)

    # Make a string representation of that list.
    timeflies = str(fruits)

    # Put a single line feed after that string and dump it
    #   to the output file.
    outfile.write(timeflies + '\n');
    print (timeflies)

为了清楚说明,timeflies是一个如下所示的字符串:

"['apple', 'kumquat', 'persimmon', 'pineapple', 'tomato']"

这不是一个清单;它是一个字符串,看起来像下一个你可能想要使用的列表。也许有用的下一步可能是

timeflies = '\n'.join(fruits)

但是,你仍然浪费了你的循环(它只能执行一次)而丢失了第一行。你知道(失败)是如何工作的吗?

<强> SOLUTION:

infile = open("unsorted_fruits.txt", "r")
outfile=open("sorted_fruits.txt","w")

# Make a list of the input fruits
fruit_list = []
for line in infile:
    fruit_list.extend(line.split())

# Sort that list
fruit_list.sort()

# Print it to the output file, one line at a time
for fruit in fruit_list:
    print(fruit, file=outfile)

输入文件:

banana
pineapple
tomato
kumquat
apple
persimmon

输出文件:

$ cat sorted_fruits.txt 
apple
banana
kumquat
persimmon
pineapple
tomato