Python Writing output to file in directory - python

At the moment I have a piece of code that writes the output from previous lines into a .html file in the same location as where the .py file is at....
I am looking for a line of code where it will simply write into the folder ./output/ of the same location the .py file is located
Below is the code I have but cant seem get it to work...
fullhtml = '<html><body><pre><h1>%s</h1><h2>#KCBB</h2><table>%s</table></pre></body></html>'%(end_date,myhtml)
with open('%s KCBB Bands.html'%end_date, 'w') as f:
f.write(fullhtml)

it usually writes it to that location, however, you can use __file__ to refer to that location.

__file__ will give you the python file root.
import os
print(os.path.dirname(os.path.realpath(__file__)))

As mentioned, the filename of your script is in __file__ (unless you are running in an IDE like jupyter). You can just use it with functions in the os module to get that path you want.
import os
fullhtml = '<html><body><pre><h1>%s</h1><h2>#KCBB</h2><table>%s</table></pre></body></html>'%(end_date,myhtml)
filename = os.path.join(os.path.dirname(__file__), "output",
'%s KCBB Bands.html' % end_date)
with open(filename, 'w') as f:
f.write(fullhtml)

Nevermind, i managed to figure it out....
Replacing
with open('%s KCBB Bands.html'%end_date, 'w') as f:
With
with open('./output/%s - KCBB Signal Output.html'%end_date, 'w') as f:
Notice the ./output/ < thats the directory i wanted the files to go into.

I'm new here,too. I think you're trying to keep your output files in a subdirectory of the working directory where the .py files are, is that right? If so, I think you just need to include the folder name in the open statement like so:
with open('output/%s KCBB Bands.html'%end_date, 'w') as f:
f.write(fullhtml)
The folder must already exist though, or you'll get an exception.

Related

I can't write to a file in python when using the absolute path of the file

I have created a script to write to a file in python:
a_file = open("file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
The absolute path of the file is: file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt
However, the program does not write(append) to the file. I can run the program, but nothing happens to the file. The strange thing is that it works if I put the file in the same directory as the script and run the script using the location "testfileTryToOVERWRITEME.txt". That is:
a_file= open("testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
This works 100% and appends to the file. But when I use the absolute path of the file, it never works. What is wrong?
Edit
I tried everything and it still doesn't work
My code:
a_file= open("C://Users//xdo//OneDrive//Desktop//Javascript//read%20and%20write//testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
a_file.close()
This did not work. I also tried:
a_file= open("C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")
a_file.close()
This did not work
Edit (finally works)
It finally works. I replaced the "%20" with a regular space " " and used the pathlib module like this:
from pathlib import Path
filename = Path("C:/Users/qqWha/OneDrive/Desktop/Javascript/read and write/testfileTryToOVERWRITEME.txt")
f = open(filename, 'a+')
f.write("Hello")
And now it writes to the file.
It also works using "with". Like this:
with open("c:/users/xdo/OneDrive/Desktop/Javascript/read and write/testfileTryToOVERWRITEME.txt", "a+") as file:
file.write("hello")
Try doing "with". Also, replace the %20 with a space. Python does not automatically decode this, but you shouldn't have an issue using spaces in the instance below.
with open("c:/users/xdo/OneDrive/Desktop/Javascript/read and write/testfile.txt", "a+") as file:
file.write("hello")
In this case, if the file doesn't exist, it will create it. The only thing that would stop this is if there are permissions issues.
This will work. when we open a file in python using the open function we have to use two forward slashes.
f = open('C://Users//xdo//OneDrive//Desktop//Javascript//read%20and%20write//testfileTryToOVERWRITEME.txt', 'a+')
f.write("writing some text")
f.close()
or you can use another way in which you have to use from pathlib import Path package.
from pathlib import Path
filename = Path("C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt")
f = open(filename, 'a+')
f.write("Hello")
f.close()
If still, your problem exists, then try another absolute path like "C:/Users/xdo/OneDrive/Desktop/testfileTryToOVERWRITEME.txt"

How do I write to files that are inside of files which the script is not in?

I need to figure out how to fix this code:
path = "/Folder/Test.txt"
with open(path,"r+") as f:
line = f.readline()
print(line)
It needs to be able to write to the text document "Test.txt" in the folder named "Folder"
First your path should be relative:
path = "./Folder/Test.txt"
if you want to write to a file you need "w" instead of "r" in the open function
Read:
with open(path, "r") as f:
line = f.readline()
print(line)
Write:
with open(path, "w") as f:
f.write("Hello world!")
Using "w" will replace all the current content of the file. If you want to append to the file instead, you should use "a".
path should be in /absolute/location/of/file/filename.
That means either "C:/file/path/you/want/filename" in Windows or "/absolute/path/of/your/file/filename" in *nix
You can also use relative paths if the path you want is nearby (shares a directory, etc.)
For example: if the script is in /user/scripts and you want to save in /user/textfiles/Folder, you can do ../textfiles/Folder
Also make sure that the folder exists, else, it will cause an error as well.
Anyway, as you go further in python, it is recommended that you check out the os module as it can help you a lot with file paths and other things

Opening multiple files in Python before closing previous?

I have a noob python question... so bear with me.
Can I open multiple files before closing the previos.
So... can I run
import os
files=[]
for file in os.listdir(os.curdir):
files.append(open(file,'w'))
Then edit each file as I want and finish with
for file in files:
file.close()
Thanks in advance
Seems legit and works fine.
Doing operations would be hard for you this way. the list "files" doesn't contain the filenames. You would not know which file is what.
It is perfectly fine to open each file using open and later close all of them. However, you will want to make sure all of your files are closed properly.
Normally, you would do this for one file:
with open(filename,'w') as f:
do_something_with_the_file(f)
# the file is closed here, regardless of what happens
# i.e. even in case of an exception
You could do the same with multiple files:
with open(filename1,'w') as f1, open(filename2,'w') as f2:
do_something_with_the_file(f)
# both files are closed here
Now, if you have N files, you could write your own context manager, but that would probably be an overkill. Instead, I would suggest:
open_files = []
try:
for filename in list_of_filenames:
open_files.append(open(filename, 'w'))
# do something with the files here
finally:
for file in open_files:
file.close()
BTW, your own code deltes the contents of all files in the current directory. I am not sure you wanted that:
for file in os.listdir(os.curdir):
files.append(open(file,'w')) # open(file,'w') empties the file!!!
Maybe you wanted open(file, 'r') or open(file, 'a') instead? (see https://docs.python.org/2/library/functions.html#open)
Your solution will certainly work but the recommended way would be to use contextmanager so that the files gets handled seamlessly. For example
for filename in os.listdir(os.curdir):
with open(filename, 'w') as f:
# do some actions on the file
The with statement will take care of closing the file for you.

importing txt files into python

a01:01-24-2011:s1
a03:01-24-2011:s2
a02:01-24-2011:s2
a03:02-02-2011:s2
a03:03-02-2011:s1
a02:04-19-2011:s2
a01:05-14-2011:s2
a02:06-11-2011:s2
a03:07-12-2011:s1
a01:08-19-2011:s1
a03:09-19-2011:s1
a03:10-19-2011:s2
a03:11-19-2011:s1
a03:12-19-2011:s2
this is saved in animallog1.txt. How would I import this file so that it can be used to write code, or answer questions using the above data.
I have tried:
open('C:/animallog1.txt', 'r')
but it does not work and states
FileNotFoundError: [Errno 2] No such file or directory: 'C:/animallog1.txt'
Could someone please help me fix this
open('C:\\animallog1.txt', 'r')
Does file animallog1.txt exists?
On Windows you should be care for the backsplash.
file = open('c:\\path\\to\\file', 'r')
or
file = open(r'c:\path\to\file', 'r')
Check your workspace, u can use os.chdir() to change your directory to c:\?
First, if you're using Windows, you have to use backslashes. There are a couple ways to do that: one is with double backslashes as others have pointed out, another is using the various constants and functions in the os and os.path libraries:
import os
filename = "C:" + os.sep + "animallog1.txt"
Second, the "proper" way to do this is with a with statement:
with open(filename) as f: #'r' is default
for line in f:
a, date, s = line.split(":")
# ...
What the with statement does is guarantee that the file gets closed on leaving the with block. Otherwise the file doesn't get closed until the Python garbage collector gets around to it.

IO operation failure

This is the code:
def edit(aFile):
s = ''
filename = getMediaPath() + aFile
inputfile = open(filename, 'r')
read = inputfile.readlines()
inputfile.close()
for lines in read:
lines = lines.lower()
lines = lines.replace("it's", "this is")
lines = lines.capitalize()
s = s + str(lines)
newfile = getMediaPath() + 'happyEdited.txt'
x = open(newfile, 'w')
x.write(s)
x.close()
The error I get is on the "inputfile = " line. It says:
"I/O operation failed.
I tried to read a file, and couldn't. Are you sure that file exists? If it does exist, did you specify the correct directory/folder?"**
I've tried entering aFile as a string with the media path. I've tried setting aFile equal to it's media path but nothing works. When I take the parameter out and replace aFile in the code with the name of the .txt file the code works.
Thank y'all!
A few suggestions:
You could include a checking routine for debugging, e.g.,
import os
print os.path.exists(filename)
print os.path.isfile(filename)
And also, I would recommend to use
with open(filename,'r') as inputfile:
# do your stuff
instead of
inputfile = open(filename, 'r')
# do your stuff
inputfile.close()
Because with makes sure that the file stream will be definitely closed if a problem occurs in the # do your stuff section, otherwise you have to use excepts to ensure it, which is just a little bit more effort. with is just a more convenient way.
And I think what you need to get your case to work could be:
newfile = getMediaPath() + '/happyEdited.txt'
I am just adding kwatford`s comment as answer in here. What you need to change is
filename = os.path.join(getMediaPath(),aFile)
newfile = os.path.join(getMediaPath() , 'happyEdited.txt')
The main problem here is probably that you are using simple strings that represent relative file paths. If you were to provide a full traceback, then I could give you a better answer.
Now, this will give you problems a lot of the times, and so it is best practice to always use absolute paths.
Now, what is an absolute path, you say? Well, its the path that goes all the way from your drive to your actual file destination. For example: C:/Foo/Bar/Cheese/happy.py. A relative file path is a path relative to your current directory. For example you were in your command line and you were # C:/Foo/Bar/Cheese/happy.py, and if there was another file in the same directory, say more.py, then you could reference it as ./more.py, but this can lead to several problems as you are facing right now.
So, what is the solution? Like I said, use absolute paths, now how do you do this? Well you use a module called os.
So, something like this:
import os
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "name_of_file_in_current_dir")).replace(os.pardir, "/")
Now let me tell you what this means, os.path.abspath gives you an absolute path. os.path.join allows you to join paths in a flexible ways, you can join folders. os.path.dirname gives you the absolute path a specified file, in this case __file__. __file__ is a special variable. Finally, internally an OS can use different ways to separate directories, some use //, some use \, some use \\. Now, this is what works best /, since it works on all systems. We use os.pardir because it will work on all systems, Windows, Linux and Unix, which makes your code portable! :D
Also, a good recommendation would be using the with statement. Like so:
with open(file_path) as file:
This is the same as putting a try/catch block around it, but in once simple line. It also opens and closes the file stream for you.

Categories

Resources