unable to create a text file using python - python

I am trying to learn the file I/O in python, I am trying following code to generate a text file in D drive of my computer with the statements written in the code but the compilation fails saying that the file 'I want to create' is not available which is obvious. How to create the file then?
file = open(r'D:/pyflie/text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
and the error shown is
C:\Users\ssgu>python D:/pyfile/fw.py
Traceback (most recent call last):
File "D:/pyfile/fw.py", line 1, in <module>
file = open(r'D:/pyflie/text.txt',"w")
FileNotFoundError: [Errno 2] No such file or directory:
'D:/pyflie/text.txt'

You will get such an error if one of the specified directories does not exist. In this case, D:/pyflie/ does not exist yet, so it must be created beforehand. Then, your code should create and open the file normally. You can check upfront:
import os
if not os.path.exists(r"D:\pyflie"):
os.makedirs(r"D:\pyflie")
file = open(r'D:\pyflie\text.txt',"w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
file.close()
Also, check for typos in the path name. Did you mean D:/pyfile/?

Related

FileNotFoundError: Can't reach my directory path of multiple text files

I am trying to reach to the directory path of my edited text files with no success. This is my script:
contents = ["The document is only available for reading",
"Summary of family root work",
"Japan Culture: Long life"]
filenames = ["doc.txt", "report.txt", "representation.txt"]
for content, filename in zip(contents, filenames):
file = open(f"../Files/{filename}", 'w')
file.write(content)
The code generates the following error:
Traceback (most recent call last):
File "C:\Python\App1- To do list\venv\Bonus\bonus5.py", line 8, in <module>
file = open(f"../Files/{filename}", 'w')
FileNotFoundError: [Errno 2] No such file or directory: '../Files/doc.txt'
Note, the code written in a python file under different directory than the expected name "Files". The directory "Files" is existing but python don't interprets it. I expect to see the modified content for each text file. Please guys, how can I fix this problem?

How to solve - IOERROR : Fatal Error: File 'path/to/file' could not be located or is not readable

I have been trying to open a file by passing it as an argument.
I have been providing the correct file path and the file is also readable.
I created another script in order to determine whether the file is readable or not. I got the contents of the text file which shows that the file is readable and the path is also correct.
here is the piece trying to read the file -
try:
with open(args.filepath, "r") as file:
data = file.read()
except IOError:
print("Fatal Error: File "+args.filepath+" could not be located or is not readable.")
exit()
The file should be readable in the first place.

Creating text file: IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'

I am trying to write to create and write to a text file. However, the error
Traceback (most recent call last):
File "/Users/muitprogram/PycharmProjects/untitled/histogramSet.py", line 207, in <module>
drinktrainfile = open(abs_file_path, "w")
IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'
shows up. There are other instances of this in Stack Overflow, however, none of these deal with creating and writing a new file. The directories all exist however- only the file is being created The code that does this is:
import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] # i.e. /path/to/dir/
rel_path = str(j) + "/train.txt" # HR/train.txt
abs_file_path = os.path.join(script_dir, rel_path) #/path/to/dir/HR/train.txt
drinktrainfile = open(abs_file_path, "w")
EDIT: train.txt shows up, except as a directory. How do I make it a text file?
The resource is actually a directory. It was very likely a mistake, as it is not likely that somebody would have created a directory by that name. First, remove that directory, and then try to create and open the file.
You can open the file with open('/Users/muitprogram/PycharmProjects/untitled/HR/train.txt', 'w'), assuming that the file does not already exist.

How do I change/choose the file path in Python?

I'm trying to access a .txt file in Python and I can't figure out how to open the file. I ended up copying the contents into a list directly but I would like to know how to open a file for the future.
If I run this nothing prints. I think it's because Python is looking in the wrong folder/directory but I don't know how to change file paths.
sourcefile = open("CompletedDirectory.txt").read()
print(sourcefile)
The file CompletedDirectory.txt is probably empty.
If Python could not find the file, you would get a FileNotFoundError exception:
>>> sourcefile = open("CompletedDirectory.txt").read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'CompletedDirectory.txt'
Note that using read() in this way is not recommended. You're not closing the file properly. Use a context manager:
with open("CompletedDirectory.txt") as infile:
sourcefile = infile.read()
This will automatically close infile on leaving the with block.
You can get the current working directory:
import os
os.getcwd()
Then just concat it with the file container directory
os.path.join("targetDir", "fileName")

How to wait for a folder/file to be complete to finally process it in Python?

I'm trying to code a little script that watches a defined directory with a while-loop. Every file or directory that is in this directory is compressed to RAR and moved to another directory after the process is completed.
My problem: everytime I copy a file or folder to this directory, the script doesn't wait and startes the process the second it sees a new file or folder. But when the files or folders are bigger than a few kilobytes the loop breaks with a permission error.
Since I'm a Python beginner I don't know which module to use. Is there a checking module to see if the file or folder that the tool wants to process is used by another process? Or am I going in the wrong direction?
Edit: added the code for directory-only listening:
watchDir = "L:\\PythonTest\\testfolder\\"
finishedDir = "L:\\PythonTest\\finishedfolders\\"
rarfilesDir = "L:\\PythonTest\\rarfiles\\"
rarExe = "L:\\PythonTest\\rar.exe"
rarExtension = ".rar"
rarCommand = "a"
while True:
dirList = [name for name in os.listdir(watchDir) if os.path.isdir(os.path.join(watchDir,name))]
for entryName in dirList:
if not os.path.exists((os.path.join(finishedDir,entryName))):
sourcePath = os.path.join(watchDir,entryName)
entryNameStripped = entryName.replace(" ", "")
os.chdir(watchDir)
archiveName = rarfilesDir+entryNameStripped+rarExtension
subprocesscall = [rarExe, rarCommand, archiveName, entryName]
subprocess.call(subprocesscall, shell=True)
shutil.move(sourcePath,finishedDir)
When I run the script and try to add a file of several GB (named #filename# in the following lines) these errors occur:
Creating archive L:\PythonTest\rarfiles\#filename#.rar
Cannot open #filename#
The process cannot access the file, since it's used by another process.
Adding #filename# OK
WARNING: Cannot open 1 file
Done
Traceback (most recent call last):
File "C:\Python34\lib\shutil.py", line 522, in move
os.rename(src, real_dst)
PermissionError: [WinError 5] Access denied: #filepath#
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "L:/Python Test/test.py", line 35, in <module>
shutil.move(sourcePath,finishedDir)
File "C:\Python34\lib\shutil.py", line 531, in move
copytree(src, real_dst, symlinks=True)
File "C:\Python34\lib\shutil.py", line 342, in copytree
raise Error(errors)
shutil.Error: #filepath#
instead of using os.listdir, you can use os.walk, os.walk yields 3 tuple dirpath(path of directory,filenames(all files in that dirpath),dirnames(all the sub directories in dirpath)
for x,y,z in os.walk('path-of-directory'):
do you stuff with x,y,z the three tuples

Categories