I can not read file from specified directory - python

I tried to read the file from directory but i m unable to read. every time i get the same error. hello.txt is the file name and it contains the content as well. I want to read the file first and then its content line by line.
import cv2
f = open("C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt", "r")
print(f.readline())
f.close()
.
Traceback (most recent call last):
File "<ipython-input-9-b53fed7bb3dd>", line 3, in <module>
f = open("C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt'

Try out with this code -
with open(r"C:\\Users\\Kazmi-PC\\OneDrive\\Desktop\\hello.txt", "r") as file:
<some code>
This will tell that it is raw string.
More Information
What exactly do "u" and "r" string flags do, and what are raw string literals?
EDIT:
Python was not able to find file hello.txt which in real was getting passed as hello.txt.txt
Simple step on windows to view the extension:
Press window
Search "File Explorer Options"
In view tab, uncheck "Hide extensions for known file types".

Have you tried using forward slash instead of backslash?
Please try changing the directory string to:
"C:/Users/Kazmi-PC/OneDrive/Desktop/hello.txt"
It seems like this issue is similar to the one described here

Related

open() - Opening a file created via UI vs. via Console

I am starting Python and this is my first question on Stack Overflow.
I was doing some files handling recently and came up to an Error when trying to open a file to test it.
f = open("fi.txt", "r")
The problem is, I always run into an error like this:
Traceback (most recent call last):
File "C:\Users\USER\OneDrive\Documents\Python\Beginner\FileHandle2.py", line 9, in <module>
f = open("fi.txt", 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'fi.txt'
The path has been specified (via sys.path).
The file exist and it is placed in the same folder as my Python script (which is FileHandle2.py).
I do not understand what I am doing wrong here, if someone could give me some hint?
Moreover, when I do the following:
with open("fi2.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
The file "fi2.txt" is correctly created in my folder and I can call it without error when doing:
f = open("testy.txt", 'r')
Hence, I would like some hint on what is going on?
"fi.txt" was created with the UI (in Windows 10, right click > New > Text Document) while "fi2.txt" was created via the Python console.
Until now I know what to do, but I wanted to have explanation on this behavior.
Thank you peeps!
I found why, and it is really dumb.
When you create a Text file on Windows 10, you don't actually need to add the .txt extension, Windows 10 automatically add it. Also, the text files will show no extension as well.
I was quite used to type the extension myself tbh, so I never paid attention about the text files I was making.
Basically, on VS Code, the name of my file was:
fi.txt.txt

Writing to a file errors and permission errors

while True:
try:
enterName = input("Enter the name of the file:") + ".txt"
latinFile = open(enterName,"r")
read = latinFile.readlines()
for lines in read:
store.append(lines.strip())
checkSquare (store)
print ("File:")
for content in store:
print (content)
saveData(store)
I think the problem is with the code for saving the file contents.
The aim is for the code to open the file,read the contents and it checks to see if the format of the file is correct etc and then if that is all true and it works, it will save the file again (saveData) but it will rename the file so that it says in the directory that it has been validated.
However, the code isn't working ( the os.rename part) and also I keep getting a permissionerror and I don't know how to fix it.
Error message:
Traceback (most recent call last):
File "C:\Users\---\Desktop\python\idkll.py", line 44,in <module>
saveData(store)
File "C:\Users\---\Desktop\python\idkll.py", line 18, in saveData
os.rename (fileName,"VALIDATED" + fileName)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'OPENEDve.txt'
You should close your files as soon as you finish reading from them or writing to them. And you should close the file before attempting to rename it. You can either use the file's .close() method, or use a with statement so that files get closed automatically.
Incidentally, your saveData() function should probably not prompt the user for the filename: just pass it the name you already have in enterName. Also, prepending "VALIDATED" to the filename is not a good strategy. It's ok if you're just using relative filenames in the current directory, but it will make a mess of a proper file path.
In response to the update:
saveFile does not contain a file name string, it's a Python object representing your open file (also known as a file handle). The name of that file is the string in enterName. So you need to do something like
os.rename(enterName, enterName + "VALIDATED")
Just swap os.rename (fileName,"VALIDATED" + fileName) and file.close() lines inside saveData() function.
You should close the file prior to trying to rename it. The error is because your program is actually using the file it is trying to rename.

python 2.7: Testing text file in idle

I m using the command testFile = open("test.txt") to open a simple text file and received the following: Does such errors occur due to the version of python one uses?
IOError: [Errno 2] No such file or directory: 'Test.txt
add an "a+" mode argument on to your open, this will create the file if it doesn't exist:
testFile = open("test.txt", "a+")
Syntax for opening file is:
file object = open(file_name [, access_mode][, buffering])
As you have not mentioned access_mode(optional), default is 'Read'. But if file 'test.txt' does not exists in the folder where you are executing script, it will through an error as you got.
To correct it, either add access_mode as "a+" or give full file path e.g. C:\test.txt (assuming windows system)
The error is independent from the version, but it is not clear
what you want to do with your file.
If you want to read from it and you get such an error, it means that your file is not where you think it is. In any case you should write a line like testFile = open("test.txt","r").
If you want to create a new file and write in it, you will have a line like
testFile = open("test.txt","w"). Finally, if your file already exists and you want to add things on it, use testFile = open("test.txt","a") (after having moved the file at the correct place). If your file is not in the directory of the script, you will use commands to find your file and open it.

Search and Replace a File Twice

I have a directory full of playlist files and each play list looks like this:
#EXTM3U
#EXTINF:116,VME MidSeal
V:\Eagle Presentation\VME_MidSeal.wmv
#EXTINF:0,IMG 1061
\Users\cla5598\Pictures\house\IMG_1061.JPG
#EXTINF:0,IMG 1062
\Users\cla5598\Pictures\house\IMG_1062.JPG
#EXTINF:0,IMG 1067
\Users\cla5598\Pictures\house\Directory\IMG_1067.JPG
#EXTINF:0,IMG 1068
First I need to Replace the directory with a new directory ... for example
\Users\cla5598\Pictures\house\ change to /New/Pictures/
Then I need to change any other "\" to "/" because there are other sub directory's
So far I have gotten the first part to work great.. but I'm having issues with the "\" to "/" part....
so far I have this and I'm getting an error with the last part:
import os
import fileinput
file_list=[]
for file in os.listdir("D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert"):
if file.endswith(".m3u8"):
file_list.append(file)
print file_list
for i in file_list:
f1 = open(i, "r")
f2 = open("D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert\\new\\" + "Pi-" + i, "w+")
for line in f1:
f2.write(line.replace("\Users\cla5598\Pictures\house\\", "/New/Pictures/"))
f1.close()
f2.close()
file_list_new=[]
for file in os.listdir("D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert\\new"):
if file.endswith(".m3u8"):
file_list_new.append(file)
print file_list_new
for b in file_list_new:
f3 = fileinput.input(b, inplace=1)
for line in f3:
line.replace("\\", "/")
f3.close()
Here is the error I'm getting:
['list1.m3u8', 'list2.m3u8']
['Pi-list1.m3u8', 'Pi-list2.m3u8']
Traceback (most recent call last):
File "D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert\Playlist_Convert.py", line 30, in <module>
for line in f3:
File "C:\Python27\lib\fileinput.py", line 252, in next
line = self.readline()
File "C:\Python27\lib\fileinput.py", line 321, in readline
os.rename(self._filename, self._backupfilename)
WindowsError: [Error 2] The system cannot find the file specified
First of all, your error is that the file you're trying to read does not exist. The reason is that your current directory (The directory from which you run the code) is probably D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert. But os.listdir returns only file names. In the second time you list the directory D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert\\new which is not your current directory. So the script tries to read files that doesn't exist. To fix this you should use full paths like this:
os.path.join(r"D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert\new", b)
Or you can use paths relative to your current directory:
os.path.join(r"new", b)
There is another problem in your code.
From the documentation:
if the keyword argument inplace=1 is passed to fileinput.input() or to
the FileInput constructor, the file is moved to a backup file and
standard output is directed to the input file
Try running your code in its current shape (Backup all the files first!). You'll see it adds the character ' around each line. This happens because when you type in the console:
a = "hi"
a
Then you get 'hi' - your string inside '. And since the standard output (the output to the console) is directed to your file, this is what happens.
So what you should do is instead of line.replace("\\", "/") do:
print line.replace("\\", "/"),
Notice the "," at the end - this is so that a new line won't be added.
And one last thing: I think this way is the wrong way to do it since there is no reason to direct standard output to your file and since using a sophisticated library is an over-kill in my opinion.
I think you should do it the same way you did the first part. Just write your output to a new file. Also, this is not relevant to your question at all, but you may want to look at how to use the with statement in python. This way you can use with open("some-file") as f: do-things() and python will close the file for you.
EDIT:
You can combine the loops and do part 1 and part 2 together:
file.write(line.replace("\Users\cla5598\Pictures\house\\", "/New/Pictures/").replace("\\", "/"))
And you can do:
for i in os.listdir("D:\Users\cla5598\Documents\Aptana Studio 3 Workspace\Playlist_Convert"):
if file.endswith(".m3u8"):
And delete the first loop.

Opening '.txt' Files in Python

Answer Has Been Decided
The problem was not listing the entire file listing (i.e. DRIVE1\DRIVE2\...\fileName.txt).
Also, note that the backslashes must be turned into forwardslashes in order for
Python to read it (backslashes are outside of the unicode listing).
Thus, using: addy = 'C:/Users/Tanner/Desktop/Python/newfile.txt'
returns the desired results.
It's been a while since I have played with Python, and for my most recent class, we are required to make a BFS search that does a Word Puzzle that the Alice in Wonderland author created. I am just stating this, as the algorithm is the homework, which I have completed. In other words, my question does not apply to the answer to my homework question.
With that out of the way, I am in need of help on how to open, edit, read, create some form of text files in Python. My real problem is to place a list of words that I have inside of a .txt file, into a Dictionary dictionary. but I would much rather do this myself. Thus, I am left with how to do the said to text files.
NOTE:
I am running v3.3.
All documentation that I have found while searching how to solve this simple problem
is in regards to 2.7 or older.
I have tried to use:
>>> import sys from argv
>>> script, filename = argv
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
I have also tried to use:
>>> f = open(newfile.txt, 'r')
But again, I get this error:
File "<pyshell#8>", line 1, in <module>
f = open (filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'newfile.txt'
However, I am positive that this file does exist. All of this being said, I am not sure if this is a directory problem, a problem understanding, or what... That is, anything would help!
First, if you want to retrieve a file name which is passed as the first argument to your script, use code like this:
import sys
if len(sys.argv) > 2:
filename = sys.argv[1]
else:
# set a default filename or print an error
Secondly, the error clearly indicates that the script can't find the file newfile.txt. So it is either not in the current directory, you don't have the permission to read it, etc...
To open a file for reading, use with command as follows
# This is python 3 code
with open('yourfile.txt', 'r') as f:
for line in f:
print(line)
with command used together with open command has already the raising exception process.

Categories