-1

I'm new to python, I've only started trying to use it in the past couple of days. The reason why I am using it is because I have data that I need to sort, and I want to use regex code that thankfully, works to convert the data from a text file into strings that are much easier to work with, and then further sorts those strings using python so that it is only the data entries that are within the parameters I need for my research project and prints them as output.

What I planned on doing, was starting off by writing simple code that would just open the text file and print it to see if that could function properly. But I cannot manage to do it for whatever reason, I might have something installed or configured improperly but I don't know what it could be.

Here's the code:

from fileinput import close

text = open("C:\Users\buzzk\Downloads\New folder\unsortedcats.txt")
read_text = text.read()
print(text)
close()

It should be simple, but whenever I try to run it, it gives me this in the terminal:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I don't know how this can be. I took this code straight from a tutorial so I do not know how it can be improperly written. I have also tried this:

from fileinput import close

text = open("unsortedcats.txt")
read_text = text.read()
print(text)
close()

Which gives me a better error, but still an error nontheless:

FileNotFoundError: [Errno 2] No such file or directory: 'unsortedcats.txt'

The text file is open in another tab in vscode. I do not know what I am doing wrong here.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Sidenote: best practice for opening files is using `with` like `with open(filename) as f: data = f.read()`. It's covered in the official tutorial [here](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files). Otherwise, `close()` should be `text.close()`. `fileinput.close()` only works on `fileinput` inputs. – wjandrea May 27 '23 at 22:10
  • BTW, check out [ask] for tips like how to write a good title. It helps to say what the actual problem is. – wjandrea May 27 '23 at 22:16

1 Answers1

0

The error arises from the way Python interprets the backslash \ character. In a Python string, \ is an escape character, which means it's used to introduce special character sequences. For example, \n is a newline, and \t is a tab. If you want a literal backslash, you need to escape it by using \\ instead.

Try this code:

from fileinput import close

text = open("C:\\Users\\buzzk\\Downloads\\New folder\\unsortedcats.txt")
read_text = text.read() 
print(read_text) #print read_text not text
close()
wjandrea
  • 28,235
  • 9
  • 60
  • 81