简体   繁体   English

排序和打开和写入文件

[英]Sorting and opening and writing a file

I am trying to write a function that do the following我正在尝试编写一个执行以下操作的函数

  • Open the file word_list.txt打开文件 word_list.txt
  • Read the contents of this file into a list将这个文件的内容读入一个列表
  • Sort the list in alphabetical order按字母顺序对列表进行排序
  • Write the contents of the list to a file called alphabetic.txt将列表的内容写入一个名为alphabetic.txt的文件中

This is my code这是我的代码

def alphabetic():
    file = open("word-text.txt","r")
    data=file.read()
    print (data)
    file.close()
    listsort=data
    listsort.sort()
    print(listsort)

Whenever I try to run this code, the list that I used "file" won't be sorted and I get the following results (which is the same list order that I have) and I am trying to sort them with alphabetical order with an error每当我尝试运行此代码时,我使用“文件”的列表将不会被排序,并且我得到以下结果(与我拥有的列表顺序相同),并且我正在尝试按字母顺序对它们进行排序错误

>>> alphabetic()
apples
oranges
watermelon
kiwi
zucchini
carrot
okra
jalapeno
pepper
cucumber
banana
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    alphabetic()
  File "/Users/user/Desk`enter code here`top/Outlook(1)/lab6.py", line 15, in alphabetic
    listsort.sort()
AttributeError: 'str' object has no attribute 'sort'`

Your approach wasn't working because the read method returns only a string.您的方法不起作用,因为read方法仅返回一个字符串。 Since Python strings don't have a sort() method, you got the error that you did.由于 Python 字符串没有sort()方法,因此您遇到了您所做的错误。 The sort method applies to lists as shown in my approach using the readlines method. sort方法适用于我使用readlines方法的方法中所示的lists

If this is your file's contents:如果这是您文件的内容:

apples
oranges
watermelon
kiwi
zucchini
carrot
okra
jalapeno
pepper
cucumber
banana

Here's the associated code:这是相关的代码:

with open('word-text.txt', 'r') as f:
    words = f.readlines()

    #Strip the words of the newline characters (you may or may not want to do this):
    words = [word.strip() for word in words]

    #sort the list:
    words.sort()
    print words

This outputs:这输出:

['apples', 'banana', 'carrot', 'cucumber', 'jalapeno', 'kiwi', 'okra', 'oranges', 'pepper', 'watermelon', 'zucchini']

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

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