25 blank lines in my sorted_fruits output list! - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: 25 blank lines in my sorted_fruits output list! (/thread-12079.html) |
25 blank lines in my sorted_fruits output list! - raven61 - Aug-08-2018 25 blank lines in my sorted_fruits output list don't know how to get rid of them! Don't know how they got there!here is my script # This just gives you a feel that something is happening. print('Sorting started') # This defines where the ipnput and output files are fin = open('unsorted_fruits.txt', 'r') fout = open('sorted_fruits.txt', 'w') # This reads the input file Fruits = fin.readlines() # This sorts the input file Fruits.sort() # This for loop writes the fruits to the sorted_fruits list. for fruit in Fruits: fout.write(fruit) # This cloes both files. fin.close() fout.close() # This just lets you know that the sorting is finished. print('Sorting finished')If you run it the output sorted_fruits.txt file has 25 empty lines and then the list starts. This was for home work but i've already turned it in I just want to know if I can get the lines removed? I can't figure it out. RE: 25 blank lines in my sorted_fruits output list! - buran - Aug-08-2018 I guess you have 25 blank lines at the end of your input file 'unsorted_fruits.txt' RE: 25 blank lines in my sorted_fruits output list! - Axel_Erfurt - Aug-08-2018 Does unsorted_fruits.txt come from a different os? test the line endings import os padding = 20 file = '/unsorted_fruits.txt' if os.path.isfile(file): if "\r\n" in open(file,"r").read(): print (file.ljust(padding, " ")," : DOS line endings found") if "\n" in open(file,"r").read(): print (file.ljust(padding, " "), " : UNIX line endings found") if "\r" in open(file,"r").read(): print (file.ljust(padding, " ")," : MAC line endings found") RE: 25 blank lines in my sorted_fruits output list! - raven61 - Aug-08-2018 No there are no lines on the input file. RE: 25 blank lines in my sorted_fruits output list! - buran - Aug-08-2018 Can you share your input file? I don't think it's line-ending issue because in this case it will be extra blank line between other lines. RE: 25 blank lines in my sorted_fruits output list! - raven61 - Aug-08-2018 [attachment=445] here is the unsorted_fruits txt file. RE: 25 blank lines in my sorted_fruits output list! - snippsat - Aug-09-2018 Testing file. with open('fruit.txt') as f: for line in f: print(repr(line)) So the maker of file have manged to get 2 new line \n between words.Clean up: with open('fruit.txt') as f: for line in f: line = line.strip() if line.strip(): print(line) Want a list:with open('fruit.txt') as f: lst = [line.strip() for line in f if line.strip()]
RE: 25 blank lines in my sorted_fruits output list! - raven61 - Aug-09-2018 Thank you everybody for your help! |