Opening file path not working in python [duplicate]

2024/10/2 20:38:59

I am writing a database program and personica is my test subject (I would usually have a variable in the place of the file path, but for test and demo purposes I just have a string.). There is a text file at this exact location on my computer (I have changed my username on here, by the way because I am paranoid.), but it says:

Traceback (most recent call last):
File "C:\Users\Admin\Documents\Project 
Documentation\InteractiveExecutable.py", line 46, in <module>
ReadPerson = open("C:/Users/Admin/Documents/Project 
Documentation/personica.txt", 'r')
IOError: [Errno 2] No such file or directory:
'C:/Users/Admin/Documents/Project Documentation/personica.txt'

This is the line of code:

ReadPerson = open("C:/Users/Admin/Documents/Project Documentation/personica.txt", 'r')

I am certain that it is there and when I copy that address into Windows Explorer, it takes me right to the text file.

Anyone know why this is not working?

Answer

The new-ish pathlib module (available in Python >= 3.4) is great for working with path-like objects (both Windows and for other OSes).

It's Paths - Paths all the way down

To simplify: you can build up any path (directory and file path objects are treated exactly the same) as an object, which can be an absolute path object or a relative path object. You can use raw strings to make complex paths (i.e., r'string') and pathlib will be very forgiving. However, note that there are better ways to build up paths than raw strings (see further down).

Here are examples:

from pathlib import PathPath(r'c:\temp\foo.bar') # absolute path
Path(r'c:/temp/foo.bar') # same absolute path
Path('foo.bar') # different path, RELATIVE to current directory
Path('foo.bar').resolve() # resolve converts to absolute path
Path('foo.bar').exists() # check to see if path exists

Note that if you're on Windows pathlib forgives you for using the "wrong slash" in the second example. See discussion at the end about why you should probably always use the forward slash.

Simple displaying of some useful paths- such as the current working directory and the user home- works like this:

# Current directory (relative):
cwd = Path() # or Path('.')
print(cwd)# Current directory (absolute):
cwd = Path.cwd()
print(cwd)# User home directory:
home = Path.home()
print(home)# Something inside the current directory
file_path = Path('some_file.txt') # relative path; or 
file_path = Path()/'some_file.txt' # also relative path
file_path = Path().resolve()/Path('some_file.txt') # absolute path
print(file_path)

To navigate down the file tree, you can do things like this. Note that the first object, home, is a Path and the rest are just strings:

some_person = home/'Documents'/'Project Documentation'/'personica.txt' # or
some_person = home.join('Documents','Project Documentation','personica.txt')

To read a file located at a path, you can use its open method rather than the open function:

with some_person.open() as f:dostuff(f)

But you can also just grab the text directly!

contents = some_person.read_text()
content_lines = contents.split('\n')

...and WRITE text directly!

data = '\n'.join(content_lines)
some_person.write_text(data) # overwrites existing file

Check to see if it is a file or a directory (and exists) this way:

some_person.is_dir()
some_person.is_file()

Make a new, empty file without opening it like this (silently replaces any existing file):

some_person.touch()

To make the file only if it doesn't exist, use exist_ok=False:

try:some_person.touch(exist_ok=False)
except FileExistsError:# file exists

Make a new directory (under the current directory, Path()) like this:

Path().mkdir('new/dir') # get errors if Path()/`new` doesn't exist
Path().mkdir('new/dir', parents=True) # will make Path()/`new` if it doesn't exist
Path().mkdir('new/dir', exist_ok=True) # errors ignored if `dir` already exists

Get the file extension or filename of a path this way:

some_person.suffix # empty string if no extension
some_person.stem # note: works on directories too

Use name for the entire last part of the path (stem and extension if they are there):

some_person.name # note: works on directories too

Rename a file using the with_name method (which returns the same path object but with a new filename):

new_person = some_person.with_name('personica_new.txt')

You can iterate through all the "stuff' in a directory like so using iterdir:

all_the_things = list(Path().iterdir()) # returns a list of Path objects

Sidebar: backslashes (\)

Be careful when using backslashes in a path string, especially ending a path with a backslash. As with any string, Python will read that terminating backslash as an escape character even in raw input mode. Observe:

>>> r'\'File "<stdin>", line 1r'\'^
SyntaxError: EOL while scanning string literal

So this will give a pretty cryptic error message if you are not aware of this issue:

>>> Path(r'C:\')File "<stdin>", line 1Path(r'\')^
SyntaxError: EOL while scanning string literal

The reason for this error is that \' is assumed to be a single quotation in the string. This works fine: '\'' (the second single quotation ends the string).

If you insist on using backslashes, be sure to use raw input mode or you will run into problems. For example, the '\t' character represents a tab. So when you do this (without raw input):

>>> Path('C:\temp')

You are putting a tab character into your path. This is perfectly legal and Python won't complain until you do something that causes Windows to try turning it into a real Windows path:

>>> Path('C:\temp').resolve()
Traceback (most recent call last):File "<stdin>", line 1, in <module>
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\temp'

This is also a very cryptic error if you do not know what is going on! Best to avoid the backslash characters altogether when messing about with paths.

Preventing Your Problem

Your problem occurred when you created your file and erroneously added a double extension. To prevent this issue using pathlib, use the touch method to make the file:

some_person = Path.home()/'Documents'/'Project Documentation'/'personica.txt'
some_person.touch()
https://en.xdnf.cn/q/70808.html

Related Q&A

Cython: Segmentation Fault Using API Embedding Cython to C

Im trying to embed Cython code into C following Oreilly Cython book chapter 8. I found this paragraph on Cythons documentation but still dont know what should I do:If the C code wanting to use these fu…

Computing AUC and ROC curve from multi-class data in scikit-learn (sklearn)?

I am trying to use the scikit-learn module to compute AUC and plot ROC curves for the output of three different classifiers to compare their performance. I am very new to this topic, and I am struggli…

Nested dictionary

I am working on some FASTA-like sequences (not FASTA, but something I have defined thats similar for some culled PDB from the PISCES server).I have a question. I have a small no of sequences called nCa…

How to create a Python script to automate software installation? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Using __str__() method in Django on Python 2

I am Learning Django using the Django project tutorial. Since I use python 2.7 I am unable to implement the following in python 2.7:from django.db import modelsclass Question(models.Model): # ...def _…

Losing merged cells border while editing Excel file with openpyxl

I have two sheets in an Excel file and the first one is a cover sheet which I dont need to edit. There are a few merged cells in the cover sheet, and when I edit the file using openpyxl, without even t…

Reset CollectorRegistry of Prometheus lib after each unit test

I have a class A that initializes a Counter in its initfrom prometheus_client import Counter class A:def __init__(self):self.my_counter = Counter(an_awesome_counter)def method_1(self):return 1def metho…

Why does Django ORM allow me to omit parameters for NOT NULL fields when creating an object?

Stupid question time. I seem to be able to create an object for a Django model even though I omit a column that was defined as NOT NULL and I dont understand why. Heres my model:class Movie(models.Mo…

Where should i do the django validations for objects and fields?

Im creating a django application which uses both the Django Rest Framework and the plain django-views as entrypoint for users.I want to do validation both independant fields of my models, and on object…

Why does bytes.fromhex() treat some hex values strangely?

Im trying to use the socket library in Python to send bytes of two hex digits to a piece of hardware programmed to accept them. To create the bytes from a user-entered string of hex digits, Im trying …