В вашей программе две вещи:
- Вы писали в выходной файл до того, как отсортировали ввод
- Вы включали символы новой строки в свою строку, поэтому, сравнивая последний символ, вы фактически сравнивали символы новой строки.
Вот ваша программа с комментариями об изменениях:
# mf1 = open("word.txt", "r") # Don't do this here. You read it in in your with block anyway.
# mf2 = open("word2.txt", "w+"). # Don't do this here. You write it in your with block anyway
mylist1=[]
mylist2=[]
def sort(c):
for i in mylist1:
if c==i[-1]:
mylist2.append(i)
def getListEnd(c, ifile):
with open(ifile, "r") as mf1:
for s in mf1: # the strings will still contain the newlines if read this way
# so when you check the end of the string you'll actually be comparing
# a newline character.
if "\n" in s:
mylist1.append(s[:-1]) # if there's a newline character,
# don't include it when appending to the list
else:
mylist1.append(s)
print("mylist length: ", len(mylist1))
print("mylist1: ", mylist1)
sort(c)
getListEnd('s', 'word.txt') # you don't need to pass it any info about the output file
print("mylist2: ", mylist2)
## Your writing block has to come after you've sorted it! Not before
with open('word2.txt', 'w+') as mf2:
for listitem in mylist2:
mf2.write('%s\n' % listitem)
В более общем смысле:
Чтобы создать список только с элементами, заканчивающимися буквой "s", вы можете просто сделать:
input_list = ['apples', 'carrot', 'johns', 'list']
output = [i for i in input_list if "s" == i[-1]]
print(output)
>> ['apples', 'johns']
Строка output = [i for i in input_list if "s" == i[-1]
выполняет итерацию по списку input_list
с i
и проверяет каждый элемент, чтобы увидеть, является ли последний символ каждой строки i[-1]
символом 's'
. Затем он возвращает список со всеми элементами, которые соответствуют условию. Более выразительный способ кодирования это будет:
for word in input_list:
if word[-1] == "s":
output.append(word)
С чтением и записью файлов в python безопаснее выполнять их с помощью with
операторов, так как это гарантирует, что у вас нет закрытых файлов, висящих вокруг / безопаснее с точки зрения области видимости.
Более простая версия:
Вот игрушечная программа, которая, я думаю, делает то, что вы хотите:
with open("word.txt", "r") as f:
mylist1 = f.read().split("\n") # splits the input file around newlines
mylist2 = [i for i in mylist1 if "s" == i[-1]]
with open("word2.txt", "w") as f:
for word in mylist2:
f.write(f"{word}\n") # writes word into the file
если word.txt был:
john
apples
carrots
lewis
Тогда word2.txt становится:
apples
carrots
lewis