0

I am an infant in the coding world (week 6) and I need some help! My overall goal is to write a program that inputs the file unsorted_fruits.tex, reads it, sorts the list alphabetically, and then writes it out to a file called sorted_fruits.txt.

So far I have my basics (aside from sorting and writing it into the new file)

infile=open("unsorted_fruits.tex", "r")
outfile=open("sorted_fruits.txt","w")
fruit=infile.read(26)
outfile.write(fruit)
unsorted_fruits.sort()
print (fruit)
infile.close()
outfile.close()

However I keep getting the [Errno 2] No such file or directory: 'unsorted_fruits.tex'

The file is definitely saved to my computer. I thought it might be .tex (I wasn't familiar with this format) so I changed the file to .txt. and called the .txt to see if that worked, no luck, so I changed it back to .tex Any help is appreciated, thanks!!

Eugene Primako
  • 2,767
  • 9
  • 26
  • 35
  • 2
    Is the file with the code you posted in the same directory as the text files you're trying to open? Which command are you using to run this? – Rafael Barros Dec 30 '15 at 23:02
  • It works fine for me with one exception, unsorted_fruits.sort() doesn't exist (and it shouldn't be as it isn't defined in the code). Make sure the file unsorted_fruits.tex is in the same folder (directory) as your Python script. If that doesn't work please update your question with the file paths of the three files. – Steve Byrne Dec 30 '15 at 23:05
  • An additional point; you're writing the *unsorted* input to the output file. – Roland Smith Dec 30 '15 at 23:31
  • I just checked the directories, unsorted_fruits.tex was in Downloads and my Python program was in Documents. Changed it and it works now. Thank you guys! Will probably be posting again very soon as I'm unsure about how to sort a list alphabetically. – TaylorMoon Dec 30 '15 at 23:32
  • @TaylorMoon If your data is on several lines in the file, use the `readlines` method instead of `read`. This returns a list of lines. Sort that list and write the sorted list to the output file with `writelines` instead of `write`. – Roland Smith Dec 30 '15 at 23:35

1 Answers1

0

Your code tries to find the text file in current directory. (For example, it can be the directory where Python interpreter is installed). So you may want to specify the absolute path. if text files are in the same dir with python script, you may want to use something like:

file_name = os.path.join(os.path.dirname(__file__), 'unsorted_fruits.tex')
with open(file_name, 'r') as f:
    data = f.read()

(Note: I'm using "with" syntax while working with file, so I do not need to close it manually)

Eugene Primako
  • 2,767
  • 9
  • 26
  • 35