-1

I'm struggling to save my multiple text files reviews to code it in python this is my code for it:

print("Similarity Value: " + str(similarity))
print("Most Similar Watch: ")
print(mostSimilar)

with open("{}.txt".format(casebase[mostSimilar][0])) as review1:
    print(review1.read())

with open(filepath, "a") as myfile:
    myfile.write('\n')
    myfile.write(str(unknowncase))

if __name__ == '__main__':
    main()

what this shows now when I run it says:

[Errno 22] invalid mode ('r') or filename: ' "L watch".txt'

but the files does exist in the specified folder too im not sure what the problem is.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
james
  • 1
  • 2
    You're attempting to *read* from a file that doesn't exist. This makes no sense. I assume this is the first `open()` call? The way your error is printed now, it looks like the filename you're trying to open is ` "L watch".txt` (just like that, with the space at the start and `"`) ... That doesn't sound quite correct to me ... – Martin Tournoij Mar 22 '16 at 14:53
  • the file does exist as a text file but it cant find it and throws that error to me and yes it knows which text file to open which is the L text file but it says that file is not found when its there – james Mar 22 '16 at 14:59
  • Your mean to say you have a text file: '"L watch".txt'? look at the quotes in the error and check the filename – DCA- Mar 22 '16 at 15:02
  • Possible duplicate of [IOError: \[Errno 22\] invalid mode ('r') or filename: 'c:\\Python27\test.txt'](http://stackoverflow.com/questions/15598160/ioerror-errno-22-invalid-mode-r-or-filename-c-python27-test-txt) – Billal Begueradj Mar 22 '16 at 15:03
  • Are you **sure** that the file exists **exactly** like that, with a leading space and the quotation marks and the L? – Martin Tournoij Mar 22 '16 at 15:03
  • 1
    Clearly your `open` call is not attempting to open what you think it is. Try setting the `format` value before the `open` call and printing it to see what it's actually attempting to open. – kungphu Mar 22 '16 at 15:03
  • filename is that and i have checked the error its still giving me the same problem – james Mar 22 '16 at 15:04

1 Answers1

0

Your error:

[Errno 22] invalid mode ('r') or filename: ' "L watch".txt'

Notice that you are trying to read "L watch".txt, this is clearly wrong, I think you are want to read L watch.txt. So your formating is substituting {} for '"L watch"' where should be substituting for L watch without quotes(").

Usually read the errors carefully help a lot with this problems. Happy hacking!!

EDIT - 2 posible solutions here:

with open("{}.txt".format(casebase[mostSimilar][0].strip('"')) as...

or

with open(filepath.replace('"', ""), "a") as myfile:

or both of them.

Netwave
  • 40,134
  • 6
  • 50
  • 93