如何使用Mac输入和输出Python文件

时间:2015-03-19 02:04:19

标签: python python-2.7

所以我查看了与我的问题类似的其他帖子,但仍然不断为我的代码收到错误。我应该在我的桌面上带一个水果列表并将其带入python,让它自行排序,然后创建一个输出文件。

我被告知outfile存在语法错误,即使这是教师给我的代码。有谁知道为什么我的代码对我不起作用?

print "Program Started"

#Input and output file given
import os

infile = open(os.path.expanduser("~/Desktop/unsorted_fruits.txt","r")
outfile = open("~/Desktop/sorted_fruits.txt","w")

#Reading of Input file
fruit=infile.read(50)

#Sorting of items in list
fruits.sort ()

for fruit in Fruits:
    if fruit <> "\n":       #If fruit is blank, skip the write
        outfile.write(fruit)    #otherwise write fruit to output file
        print (fruit)

#Closing of the input and output file
infile.close()
outfile.close()

print "Program Completed"

2 个答案:

答案 0 :(得分:1)

这里有一些问题,主要是语法错误。 具体做法是:

  • infile = open(os.path.expanduser("~/Desktop/unsorted_fruits.txt","r"))
  • 附近缺少expanduser
  • outfile不会调用expanduser并且无法正确保存
  • fruit=infile.read(50)只会将其作为字符串读取,因此将其排序为列表后,将无法正常工作
  • for fruit in Fruits - python区分大小写,所以水果需要成果

这是一个有效的版本

print "Program Started"

#Input and output file given
import os

with open(os.path.expanduser("~/Desktop/unsorted_fruits.txt"),"r") as infile:
    fruits = infile.read().splitlines()

outfile = open(os.path.expanduser("~/Desktop/sorted_fruits.txt"),"w")

#Reading of Input file
#fruits=infile.read(50)

#Sorting of items in list
fruits.sort()

for fruit in fruits:
    if fruit <> "\n":       #If fruit is blank, skip the write
        outfile.write(fruit)    #otherwise write fruit to output file
        print (fruit)

#Closing of the input and output file
#infile.close()
outfile.close()

print "Program Completed"

只是要警告 - 这不是好/干净的代码 - 它只是修复了你的错误

答案 1 :(得分:0)

由于我不知道您收到的错误或您正在阅读的文件的结构,我写这篇文章通常会告诉您应该做什么。

#import os  -> imports should always go on top fyi

with open("~/Desktop/unsorted_fruits.txt","r") as infile:
    sorted_file = sorted(infile.read().split())

with open("~/Desktop/unsorted_fruits.txt","r") as outfile:
    for item in sorted_file:
        outfile.write(item)

print "Program Completed"

希望有所帮助