Python - Problem with writing file Errno 2 - python

I am a Python newbie and I am having a problem that probably has as a simple answer. I have the following script, which works most of the way, I just get stuck trying the write the output file. The error I get is at the very end: IOError: [Errno 2] No such file or directory: '/D/1_NEW_ANALYSIS/Scripts/Melodic_fsfs/design_Rat01_Run_1.fsf'
Here is the code:
import os
import glob
studydir = 'D:/1_NEW_ANALYSIS'
fsfdir="%s/Scripts/Melodic_fsfs"%(studydir)
templatedir="%s/Scripts/Templates"%(studydir)
subdirs=glob.glob("%s/Subjects/Rat_[0-9][0-9]/Run_[0-2]"%(studydir))
for dir in list(subdirs):
splitdir = dir.split('\\')
# YOU WILL NEED TO EDIT THIS TO GRAB sub001
splitdir_sub = splitdir[1]
subnum=splitdir_sub[-2:]
splitdir_run = splitdir[2]
runnum=splitdir_run[-1:]
print(subnum)
replacements = {'SUBNUM':subnum, 'RUNNUM':runnum}
with open("%s/Melodic_design.fsf"%(templatedir)) as infile:
with open("%s/design_Rat%s_Run_%s.fsf"%(fsfdir, subnum, runnum), 'w') as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)
Anybody have an idea why it doesn't work?
Thanks a lot!

If you are running on windows (I assume you are), studydir should look like:
studydir = 'D:\\1_NEW_ANALYSIS'

Related

Issue reading file in Python

I had some problems with my Python code.
My code:
import os
logininfo = list()
with open(os.getcwd() + '/login/info.txt', 'r') as f:
logininfo = f.readlines()
But my code isn’t work, so how do I fix that?
Edit: I changed the quote and changed the ‘ to '
Problem 2: After I fix all that look like my computer is freeze now and I can’t even move my mouse. After freeze for a while, the code make my computer ran to BSOD. What happened?
Okay, I think I see what the problem in problem 2 that my file was too big with 50 GB of login information of my server. Thanks you guy for helping me solve the problem 1.
Your problem is likely that your / (forward slashes) are supposed to be \ (backslashes). It is also a good practice to use os.path.join() when concatenating file paths. Make sure login\info.txt does not have a backslash in front of it. I printed the list afterwards to make sure it was working. Windows file paths use \\.
import os
with open(os.path.join(os.getcwd(), 'login\info.txt'), 'r') as f:
logininfo = f.readlines()
print(logininfo)
Regardless of OS, I would recommend using pathlib module to deal with system paths and to decrease ambiguity in OS path handling.
So, regardless of OS, an API would be (including your code):
from pathlib import Path
file_path = Path.cwd() / 'login' / 'info.txt'
with open(file_path, 'r') as f:
login_info = f.readlines()
Get familiar with that module (it's out of the box!) here: https://docs.python.org/3/library/pathlib.html
I believe the wrong thing is that you're using double slashs, when it should be:
import os
with open(os.getcwd() + ‘/login/info.txt’, 'r') as f:
logininfo = f.readlines()
I reproduced the error here, created a file with the same folder structure as yours, and this definitely should work:
In [3]: with open(os.getcwd() + '/login/info.txt', 'r') as f:
...: lines = f.readlines()
...: for line in lines:
...: print(line)
...:
Olá,
deixa eu ver esse erro aqui

Python: Unable to open and read a file

I am totally new to python.
I was trying to read a file which I already created but getting the below error
File "C:/Python25/Test scripts/Readfile.py", line 1, in <module>
filename = open('C:\Python25\Test scripts\newfile','r')
IOError: [Errno 2] No such file or directory: 'C:\\Python25\\Test scripts\newfile
My code:
filename = open('C:\Python25\Test scripts\newfile','r')
print filename.read()
Also I tried
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
But same errors I am getting.
Try:
fpath = r'C:\Python25\Test scripts\newfile'
if not os.path.exists(fpath):
print 'File does not exist'
return
with open(fpath, 'r') as src:
src.read()
First you validate that file, that it exists.
Then you open it. With wrapper is more usefull, it closes your file, after you finish reading. So you will not stuck with many open descriptors.
I think you're probably having this issue because you didn't include the full filename.
You should try:
filename = open('C:\Python25\Test scripts\newfile.txt','r')
print filename.read()
*Also if you're running this python file in the same location as the target file your are opening, you don't need to give the full directory, you can just call:
filename = open(newfile.txt
I had the same problem. Here's how I got it right.
your code:
filename = open('C:\\Python25\\Test scripts\\newfile','r')
print filename.read()
Try this:
with open('C:\\Python25\\Test scripts\\newfile') as myfile:
print(myfile.read())
Hope it helps.
I am using VS code. If I am not using dent it would not work for the print line. So try to have the format right then you will see the magic.
with open("mytest.txt") as myfile:
print(myfile.read())
or without format like this:
hellofile=open('mytest.txt', 'r')
print(hellofile.read())

Error when trying to read and write multiple files

I modified the code based on the comments from experts in this thread. Now the script reads and writes all the individual files. The script reiterates, highlight and write the output. The current issue is, after highlighting the last instance of the search item, the script removes all the remaining contents after the last search instance in the output of each file.
Here is the modified code:
import os
import sys
import re
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f
infile = open(filepath, 'r+')
source_content = infile.read()
color = ('red')
regex = re.compile(r"(\b be \b)|(\b by \b)|(\b user \b)|(\bmay\b)|(\bmight\b)|(\bwill\b)|(\b's\b)|(\bdon't\b)|(\bdoesn't\b)|(\bwon't\b)|(\bsupport\b)|(\bcan't\b)|(\bkill\b)|(\betc\b)|(\b NA \b)|(\bfollow\b)|(\bhang\b)|(\bbelow\b)", re.I)
i = 0; output = ""
for m in regex.finditer(source_content):
output += "".join([source_content[i:m.start()],
"<strong><span style='color:%s'>" % color[0:],
source_content[m.start():m.end()],
"</span></strong>"])
i = m.end()
outfile = open(filepath, 'w+')
outfile.seek(0)
outfile.write(output)
print "\nProcess Completed!\n"
infile.close()
outfile.close()
raw_input()
The error message tells you what the error is:
No such file or directory: 'sample1.html'
Make sure the file exists. Or do a try statement to give it a default behavior.
The reason why you get that error is because the python script doesn't have any knowledge about where the files are located that you want to open.
You have to provide the file path to open it as I have done below. I have simply concatenated the source file path+'\\'+filename and saved the result in a variable named as filepath. Now simply use this variable to open a file in open().
import os
import sys
source = raw_input("Enter the source files path:")
listfiles = os.listdir(source)
for f in listfiles:
filepath = source+'\\'+f # This is the file path
infile = open(filepath, 'r')
Also there are couple of other problems with your code, if you want to open the file for both reading and writing then you have to use r+ mode. More over in case of Windows if you open a file using r+ mode then you may have to use file.seek() before file.write() to avoid an other issue. You can read the reason for using the file.seek() here.

Confusing Error when Reading from a File in Python

I'm having a problem opening the names.txt file. I have checked that I am in the correct directory. Below is my code:
import os
print(os.getcwd())
def alpha_sort():
infile = open('names', 'r')
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
infile.close()
return 0
alpha_sort()
And the error I got:
FileNotFoundError: [Errno 2] No such file or directory: 'names'
Any ideas on what I'm doing wrong?
You mention in your question body that the file is "names.txt", however your code shows you trying to open a file called "names" (without the ".txt" extension). (Extensions are part of filenames.)
Try this instead:
infile = open('names.txt', 'r')
As a side note, make sure that when you open files you use universal mode, as windows and mac/unix have different representations of carriage returns (/r/n vs /n etc.). Universal mode gets python to handle this, so it's generally a good idea to use it whenever you need to read a file. (EDIT - should read: a text file, thanks cameron)
So the code would just look like this
infile = open( 'names.txt', 'rU' ) #capital U indicated to open the file in universal mode
This doesn't solve that issue, but you might consider using with when opening files:
with open('names', 'r') as infile:
string = infile.read()
string = string.replace('"','')
name_list = string.split(',')
name_list.sort()
return 0
This closes the file for you and handles exceptions as well.

How can I edit a plain text file in Python?

I've been trying to create a python script that edits a file, but if the file is not already there, it has an error like this:
Traceback (most recent call last):
File "openorcreatfile.py", line 56, in <module>
fileHandle = (pathToFile, 'w')
IOError: [Errno 2] No such file or directory: '/home/me/The_File.txt'
It works fine if the file exists. I've also tried this:
fileHandle = (pathToFile, 'w+')
But it comes up with the same error. Do I need to explicitly check if the file is there? If so, how do I create the file?
EDIT: Sorry, I realized the folder was missing. I'm an idiot.
The error says "No such file or directory."
Since you're trying to create a file, that must not be what's missing. So you need to create the /home/me/ directory.
See os.makedirs.
fo = open("myfile.txt", "wb")
fo.write('blah')
fo.close()
That's it, this will do the job.
myfile = open('test.txt','w')
myfile.write("This is my first text file written in python\n")
myfile.close()
To check if the file is there you can do:
import os.path
os.path.isfile(pathToFile)
so you can handle it, only if it exists:
if os.path.isfile(pathToFile):
fileHandle = (pathToFile, 'w')
else:
pass #or other thing
There are several ways to create a file in python, but if you want to create a text file, take a look at numpy.savetxt, which I think is one of the easiest and most effective ways
with open("filename.txt", "w") as f:
f.write("test")

Categories

Resources