i am writing an python script. I was having some problems to open the file. The error was always that system just can not find the file.
Because of that i tried get the active path... Replace backslash ... and so on....
Is there any improvements to work with the file in the same folder?
The Code
import os
# The name of the txt file that is in the same folder.
myFile = 'noticia.txt'
# Getting the active script
diretorio = os.path.dirname(os.path.abspath(__file__))
# Replace BackSlash and concatenate myFile
correctPath = diretorio.replace("\\", "/") + "/" + myFile
# Open file
fileToRead = open(correctPath, "r")
# Store text in a variable
myText = fileToRead.read()
# Print
print(myText)
Note:
The script is in the same folder of the txt file.
Is there any improvements to work with the file in the same folder?
First off, please see PEP 8 for standard conventions on variable names.
correctPath = diretorio.replace("\\", "/") + "/" + myFile
While forward slashes are preferred when you specify a new path in your code, there is no need to replace the backslashes in a path that Windows gives you. Python and/or Windows will translate behind the scenes as necessary.
However, it would be better to use os.path.join to combine the path components (something like correct_path = os.path.join(diretorio, my_file)).
fileToRead = open(correctPath, "r")
# Store text in a variable
myText = fileToRead.read()
It is better to use a with block to manage the file, which ensures that it is closed properly, like so:
with open(correct_path, 'r') as my_file:
my_text = my_file.read()
Related
I want to modify several text-files within a folder.
I have the following code:
if command == "deployf":
for root, dirs, files in os.walk(all_posts, topdown = False):
for name in files:
if name.endswith(".html"):
file_name = os.path.join(root, name)
with open(file_name, 'r+') as fp:
lines = fp.readlines()
fp.seek(0)
fp.truncate()
fp.writelines(lines[:-9])
print('deployed to all files')
This deletes the last 9 lines in every html file in a folder. Now I want to merge (or append) the content of another .html file to the end of every file in the folder but I don`t know how.
You can ask for the path to the HTML file outside your loop:
path = input("Enter HTML File path to append to each file:")
Then read from the file:
root_content = open(path, 'r').readlines()
Then instead of removing the last 9 lines with fp.writelines(lines[:-9]), just write the root_content variable:
fp.writelines(root_content)
Im assuming this is what you want to do? You had all the knowledge shown in your problem to accomplish this, so please comment if i have misunderstood.
IIUC, you need to replace the last 9 lines of each (.html) with the content of your other file, right ?
If so, and to reduce visible noise, I would use Path.rglob from pathlib with slicing :
from pathlib import Path
if command == "deployf":
all_posts = Path(all_posts)
to_append = (all_posts / "the_other_file.html").read_text()
for html in all_posts.rglob("*.html"):
lines = html.read_text().splitlines()
html.write_text("\n".join(lines[:-9] + [to_append]))
print("deployed to all files")
If you need to replace a slice in the middle (e.g 5:10) of each (.html), use this :
lines = html.read_text().splitlines()
lines = lines[:4] + [to_append] + lines[10:]
html.write_text("\n".join(lines))
My folder structure is: C:/Users/Desktop/SampleTestFiles/ProjectFiles/ExceptionLogFiles/
Using below code, I am trying to create file in ExceptionLogFiles folder if file Exceptionlog.txt does not exists and if file exists then open the file and write some text to the file. But for some reason code is unable to detect the relative path.
Please can anyone help me in correcting code:
fileDir = 'C:/Users/Desktop/SampleTestFiles'
filename = os.path.join(fileDir, '\..\ExceptionLogFiles\ExceptionLog.txt')
#print(filename) gives: C:/Users/Desktop/SampleTestFiles/../ExceptionLog.txt
if os.path.exists(filename):
print(filename, 'exists')
#Open file and write something to the file
f = open(file, 'w')
f.write("Exception Text")
f.close()
else:
print('file not exists')
#Create File and Write something to the file.
f = open(file, 'w+')
f.write("Exception Text")
f.close()
What you tried to do was kind of like this, in an addition-like fashion
(
C:/Users/Desktop/SampleTestFiles
+
.. (which is up one directory)
)
+ ExceptionLogFiles\ExceptionLog.txt
The "parenthesized" addition will actually resolve to C:/Users/Desktop/, and we add ExceptionLogFiles\ExceptionLog.txt' to that. So we'd be looking at: `C:/Users/Desktop/ExceptionLogFiles\ExceptionLog.txt'
However, even if you dropped the ..\ from your string, those backslashes don't become literal backslashes in a string without you escaping them.
Try this (and NOTE the backslashes are doubled so as to escape backslash, which is the escape character!)
fileDir = 'C:/Users/Desktop/SampleTestFiles'
filename = os.path.join(fileDir, 'ExceptionLogFiles\\ExceptionLog.txt')
Looks like you're looking for normpath
import os
fileDir = 'C:/Users/Desktop/SampleTestFiles'
filename = os.path.join(fileDir, '../ExceptionLogFiles/ExceptionLog.txt')
print(filename)
print(os.path.normpath(filename))
result:
C:/Users/Desktop/SampleTestFiles/../ExceptionLogFiles/ExceptionLog.txt
C:/Users/Desktop/ExceptionLogFiles/ExceptionLog.txt
You can use "with open('path','a+') as f", whatever file exists or not,you can write something into it.
I am making in a python script which replaces and add a command at the end of a file. I am using:
outfilename=infile.replace(".pdb","-solv"+str(solvcycle)
+ ".pdb")
Is it possible to make this function replace .pdb or .xyz file, or more generally, to replace any extention of the infile? I need the script to replace the name of any infile as it does for pdb.
I recommend using pathlib:
from pathlib import Path
infile = 'foo/bar.xyz'
infile = Path(infile)
new_name = infile.stem + '-solv' + infile.suffix
outfilename = infile.with_name(new_name)
print( str(outfilename) )
# output: foo/bar-solv.xyz
Currently I am trying to write a function will walk through the requested directory and print all the text of all the files.
Right now, the function works in displaying the file_names as a list so the files surely exist (and there is text in the files).
def PopularWordWalk (starting_dir, word_dict):
print ("In", os.path.abspath(starting_dir))
os.chdir(os.path.abspath(starting_dir))
for (this_dir,dir_names,file_names) in os.walk(starting_dir):
for file_name in file_names:
fpath = os.path.join(os.path.abspath(starting_dir), file_name)
fileobj = open(fpath, 'r')
text = fileobj.read()
print(text)
Here is my output with some checking of the directory contents:
>>> PopularWordWalk ('text_dir', word_dict)
In /Users/normanwei/Documents/Python for Programmers/Homework 4/text_dir
>>> os.listdir()
['.DS_Store', 'cats.txt', 'zen_story.txt']
the problem is that whenever i try to print the text, i get nothing. eventually I want to push the text through some other functions but as of now it seems moot without any text. Can anyone lend any experience on why no text is appearing? (when trying to open files/read/storing&printing text manually in idle it works i.e. if I just manually inputted 'cats.txt' instead of 'file_name') - currently running python 3.
EDIT - The question has been answered - just have to remove the os.chdir line - see jojo's answer for explanation.
This line won't work
file = open(file_name, 'r')
Because it would require that these files exist in the same folder you are running the script from. You would have to provide the path to those files, as well as the file names
with open(os.path.join(starting_dir,file_name), 'r') as file:
#do stuff
This way it will build the full path from the directory and the file name.
If you do os.chdir(os.path.abspath(starting_dir)) you go into starting_dir. Then for (this_dir,dir_names,file_names) in os.walk(starting_dir): will loop over nothing since starting_dir is not in starting_dir.
Long story short, comment the line os.chdir(os.path.abspath(starting_dir)) and you should be good.
Alternatively if you want to stick to the os.chdir, this should do the job:
def PopularWordWalk (starting_dir, word_dict):
print ("In", os.path.abspath(starting_dir))
os.chdir(os.path.abspath(starting_dir))
for (this_dir,dir_names,file_names) in os.walk('.'):
for file_name in file_names:
fpath = os.path.join(os.path.abspath(starting_dir), file_name)
with open(fpath, 'r') as fileobj:
text = fileobj.read()
print(text)
You'll want to join the root path with the file path. I'd change:
file = open(file_name, 'r')
to
fpath = os.path.join(this_dir, file_name)
file = open(fpath, 'r')
You may also want to use another word to describe it than file as that's a built-in function in Python. I'd recommend fileobj.
Just to add on to the previous answer, you will have to join the absolute path and the relative path of the walk.
Try this:
fpath = os.path.abspath(os.path.join(this_dir, file_name))
f = open(fpath, 'r')
I have a txt-file called "odbList.txt" which contains the names of several odb-files.
plate_2mm.odb
plate_4mm.odb
plate_6mm.odb
Now I wrote a Python Script, where I want to open each of these files in a loop.
# list of ODB-Files
odbList = [ ]
f = file( 'W:/someDirectory/odbList.txt' , 'r')
count = 0
for line in f.readlines() :
odbList.append (line)
count = count + 1
def getSIF(case, i):
odb = openOdb(path = 'W:/someDirectory/' + case)
# start analyses for each case
for i in xrange(0,count):
getSIF(odbList[i], i)
I get the following error message:
OdbError: Cannot open file W:/someDirectory/plate_2mm.odb
. *** ERROR: No such file: W:/someDirectory/plate_2mm.odb
The weird thing however is that it works perfectly fine when I hardcode the complete path.
Another weird thing. If I use this line instead:
odb = openOdb(path = case)
I get following error message:
OdbError: Cannot open file C:/Temp/plate_2mm.odb
. *** ERROR: No such file: C:/Temp/plate_2mm.odb
And if I transfer all my files into C:/Temp everything works fine. But why doesn't it work if I use the first version / a different folder? Especially since it is working when hardcoded.
Most of the times when I open a file I use the following:
f=open(file_name,'r')
s=f.read().splitlines()
f.close()
while '' in s:
s.remove('')
You will now have a list in s without enters.
Alternatively you can use something like
import os
odbList=[]
for fileN in os.listdir("."):
if '.odb' in fileN:
odbList.append(fileN)
This will find all files containing .odb in the name in the script's directory/working directory
Have you tried entering your string as a raw string like thisodb = openOdb(path = r'W:/someDirectory/' + case) or usining the os.sep character like this: odb = openOdb(path = 'W:someDirectory' + os.sep + case)