python 2.7: Testing text file in idle - python

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.

Related

I can not read file from specified directory

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

How to create a file in a different directory? (python)

I am currently stuck with the following error:
IOError: [Errno 2] No such file or directory: '/home/pi/V1.9/Storage/Logs/Date_2018-08-02_12:51.txt'
My code to open the file is the following:
nameDir = os.path.join('/home/pi/V1.9/Storage/Logs', "Date_" + now.strftime("%Y-%m-%d_%H:%M") + ".txt")
f = open(nameDir, 'a')
I am trying to save a file to a certain path, which is /home/pi/V1.9/Storage/Logs. I am not sure why it can't find it, since I have already created the folder Logs in that space. The only thing being created is the text file. I am not sure if its suppose to join up like that, but I generally tried to follow the stages on this thread: Telling Python to save a .txt file to a certain directory on Windows and Mac
The problem seems to be here:
f = open(nameDir, 'a')
'a' stands for append, which means: the file should already exist, you get an error message because it doesn't. Use 'w' (write) instead, Python will create the file in that case.
If you are creating the file use the write mode w or use a+
f = open(nameDir, 'w')
f = open(nameDir, 'a+')
Use only a append if the file already exist.
Not really an answer to your question, but similar error. I had:
with open("/Users//jacobivanov/Desktop/NITL/Data Analysis/Completed Regressions/{0} Temperature Regression Parameters.txt".format(data_filename), mode = 'w+') as output:
Because data_filename was in reality a global file path, it concatenated and looked for a non-existent directory. If you are getting this error and are referring to the file path of an external file in the name of the generated file, check to verify it isn't doing this.
Might help someone.

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 3.4.3 unable to write to a file in a desktop folder

I have a simple code to write a file in a specific folder. System creates the file in the folder but couldn't write on it. It is on windows and I checked the IDE write access (Pycharm) they seems fine. File is empty.
Following with code is to read whether I could write or ensure the previous one is finished. It is not writing the short string to the file. I have tried it on command line but it didn't work there also.
with open ('C:/Users/***/Desktop/***/output.log',mode ='w', encoding ='utf-8') as a_file:
a_file.write ="test"
with open ('C:/Users/***/Desktop/***/output.log', encoding ='utf-8') as a_file:
print(a_file.read())
The write is a method (function), you need to call, instead of assigning to it.
with open ('C:/Users/***/Desktop/***/output.log', mode='w', encoding='utf-8') as a_file:
a_file.write("test") # <---

Find&Replace using Python - Binary file

I'm attempting to do a "find and replace" in a file on a Mac OS X computer. Although it appears to work correctly. It seems that the file is somehow altered. The text editor that I use (Text Wrangler) is unable to even open the file once this is completed.
Here is the code as I have it:
import fileinput
for line in fileinput.FileInput("testfile.txt",inplace=1):
line = line.replace("newhost",host)
print line,
When I view the file from the terminal, it does say "testfile" may be a binary file. See it anyway? Is there a chance that this replace is corrupting the file? Do I have another option for this to work? I really appreciate the help.
Thank you,
Aaron
UPDATE: the actual file is NOT a .txt file it is a .plist file which is preference file in Mac OS X if that makes any difference
LINK to plist file:
http://www.queencitytech.com/plist.zip
Your code worked for me fine. However, I would suggest a different approach: don't try overwriting the file directly. I never like changing the file directly because if you have a bug or something like that the file is lost. Generate a new file then copy it over manually (or within python, if you really want to).
PATH = 'testfile.txt'
FILE = open(PATH)
OUT_FILE = open('out_' + PATH, 'w')
for line in FILE.readlines():
print >> OUT_FILE, line.replace('newhost', host),
Try using sys.stdout.write instead of print. readlines() retains the new line characters at the end of the read line. The print statement adds an additional new line character, so it's likely double spacing the file.

Categories