Where is file located when using "with open"? - python

when I write in python this code:
with open(FileName, "w") as ans_writer:
ans_writer.write(ans_table)
Where is the FileName file saved?
If I don't have such file does it creates it?
How can I change the directory where it saves the file ?

The file will be saved to your working directory, you can get the current working directory with os.getcwd(). By default it will be the folder the script is saved in.

Straight from the manual, which I'd advise you to learn to use:
file is a path-like object giving the pathname (absolute or relative
to the current working directory) of the file to be opened or an
integer file descriptor of the file to be wrapped.
Following the link to see what a "path-like object" is, you find:
An object representing a file system path. A path-like object is
either a str or bytes object representing a path, or an object
implementing the os.PathLike protocol.
You can of course delve into what os.PathLike is, but for your uses the first definition probably suffices: FileName is a string representing the path to the file in question. "foo.txt" refers to the file "foo.txt" in your current working directory. If you don't know what this means, it's likely to be the directory you're in when you run your program. Absolute paths (like /path/too/somewhere or C:\path\to\somewhere) may be OS-dependent.

Related

Reading file in python on the Mac

I am very new on this platform and I need help reading a file in python. First, it was a docx file because I am using Mac, I converted it into a txt file ,but still have file not found error.
Here is some code:
opdoc = open('PRACT.txt')
print(opdoc.readline())
for each in opdoc :
print(each)
and this the error output: FileNotFoundError: [Errno 2] No such file or directory: 'PRACT.txt'
Unless your file is in the exact same directory as your python file, you'll get this error. Even then, it's best practice to include some sort of relative filepath, like "./PRACT.txt". In general, your issue stems from the fact that Python doesn't know where to look for your file, and where it does know to look, the file isn't there. You need to provide the full path to the file, like:
with open("path/to/file/PRACT.txt", "rb") as f:
# read file etc
Make a new folder and put the txt file in it and also the programme itself. Or just put them in the same directory.
As you have this error ( No such file or directory: 'PRACT.txt') your code couldn't find the file because they were not in the same directory. When you use open("README.txt") the programme is assuming that the text is in the same directory as your code. If you don't want them in the same directory you could also try open(f"[file_path]") and that should work.

Python can't find where my txt file is, how can i link it or where do i need to put the file?

Python can't find where my .txt file is, how can I find the correct path to it or where do I need to put the file?
I tried the following but got an error:
with open("C:\Users\raynaud\Downloads\notlar.txt","r",encoding="utf-8") as file:
with open("dosya.txt","r",encoding= "utf-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'dosya.txt'
If you are not using absolute path, you must place the file in the same directory as the script is. On absolute paths you should not use \ like "C:\Users\UserName\", because \ is the escape character in Python (and many more languages). You must use it like this: "C:\\Users\\UserName\\"
Have you checked your current directory? It might be pointing to somewhere unexpected. Try:
import os
os.getcwd()

WindowsError when using os.listdir and os.stat of the result

I have the following snippet of code that just gets the Timestamp of the file.
files_list = os.listdir(os.path.join(path, folder))
for files in files_list:
stats = os.stat(os.path.join(path, folder, files))
Is it possible for me to ever get the below error as it seems counter intuitive that it is not able to find a file that it has just got in listdir, except ofcourse for a race condition which is not what I suspect in this case.
WindowsError: [Error 2] The system cannot find the file specified:
'\\\\sftp-server.domain.com\\homes\\server\\location\\FOLDER\\FILE.PDF'
I also wonder if something like domain lookup/temporary network issue can cause this error? For example
\\sftp-server.domain\\homes\\server\\location\\FOLDER
and
\\sftp-server.domain\\homes\\server\\location\\FOLDER\FILE
are just URL Strings and has nothing to do with the real file system traversal.
Presumably FOLDER and FILE are not actual names? Take a careful look at the file names reported by the WindowsError. If they contain question marks in the last component, you have an issue with Unicode file names. Specifically, when the directory contains a file name with Unicode characters not representable in the current code page (such as Japanese characters in a Western or Eastern European locale), os.listdir will return file names with unrepresentable Unicode characters converted to ?. Obviously, such essentially broken names cannot be passed to the IO functions such as open or os.stat.
To fix this, request Unicode file names from os.listdir by passing it the directory as a Unicode string. These will contain correct characters and can be passed to os.stat, which will internally call the wide API:
dirname = unicode(os.path.join(path, folder), 'mbcs')
file_list = os.listdir(dirname)
for filename in file_list:
stats = os.stat(os.path.join(dirname, filename))
# ...
The server was doing multi-threading and we send multiple Ajax requests in a single Javascript method to the same folder resource.
In the event of os.listdir processing first this error occurs because it takes a long time to execute it over SFTP. During this time the os.remove happened in another request and removed the file that was showing up in os.listdir result. After making he os.listdir function as a proper callback it worked just fine.

File does not exist error with 'w' mode

I am encountering an odd behaviour from the file() builtin. I am using the unittest-xml-reporting Python package to generate results for my unit tests. Here are the lines that open a file for writing, a file which (obviously does not exist):
report_file = file('%s%sTEST-%s.xml' % \
(test_runner.output, os.sep, suite), 'w')
(code is taken from the package's Github page)
However, I am given the following error:
...
File "/home/[...]/django-cms/.tox/pytest/local/lib/python2.7/site-packages/xmlrunner/__init__.py", line 240, in generate_reports
(test_runner.output, os.sep, suite), 'w')
IOError: [Errno 2] No such file or directory: './TEST-cms.tests.page.NoAdminPageTests.xml'
I found this weird because, as the Python docs state, if the w mode is used, the file should be created if it doesn't exist. Why is this happening and how can I fix this?
from man 2 read
ENOENT O_CREAT is not set and the named file does not exist. Or, a
directory component in pathname does not exist or is a dangling
symbolic link.
take your pick :)
in human terms:
your current working directory, ./ is removed by the time this command is ran,
./TEST-cms.tests.page.NoAdminPageTests.xml exists but is a symlink pointing to nowhere
"w" in your open/file call is somehow messed up, e.g. if you redefined file builtin
file will create a file, but not a directory. You have to create it first, as seen here
It seems like the file which needed to be created was attempted to be created in a directory that has already been deleted (since the path was given as . and most probably the test directory has been deleted by that point).
I managed to fix this by supplying an absolute path to test_runner.output and the result files are successfully created now.

How to write a whole string to a file in Python and where does the file go?

I am doing an assignment on text formatting and alignment (text wrapping) and I need to write my formatted string to new file. But once I have written to the file (or think I've written) where does that file go? Does it actually create a file on my desktop or am I being stupid?
This is my code:
txtFile = open("Output.txt", "w")
txtFile.write(string)
txtFile.close()
return txtFile
Cheers,
JT
The text is written to a file called "Output.txt" in your working directory (which is usually the directory from which the script has been executed).
To display the working directory, you can use:
>>> import os
>>> os.getcwd()
'/home/adam'
When you open a file without specifying a file path, the file will be created in the python scripts working directory.
Usually that is the location of your script but there are times when it may be a different place.
The os module in python will provide functions for checking and changing the working directory within python itself.
most notably:
os.chdir(path)
os.fchdir(fd)
os.getcwd()
It will create a new file called "Output.txt" in the same directory that you executed your script from. It may mean that the file can't be written to, if you're in a directory that doesn't have the appropriate permissions for your user.

Categories

Resources