How to edit file outside Python directory? - python

I'm trying to edit a file outside my Python directory(edit files inside Python directory works). my Python directory is in c:\Users\test\pycharmproject\pythonproject. while debugging, the code can see all the files that end with .txt. in my case, I want to edit test.txt.but the code does not add the string to it. the code ends without any errors.
The code:
def foo(folderPath, fileEx, text):
for file in os.listdir(folderPath):
if file.endswith(fileEx):
f=open(file, "a")
f.write(text)
f.close()
print(folderPath, fileEx)#c:\Users\test, text.txt
foo("c:\\Users\\test", ".txt", "-----")
The code needs to search all the files that end with ".txt" and add to it some string.
While I'm trying to do that without the Function I can edit that file that is outside my python directory. for example:
f=open("c:\\Users\\test\\file.txt", "a")
f.write("----")
f.close()

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"

Python Writing output to file in directory

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.

How to pass a path into a variable (Python)

at the moment my python projects opens a csv file through a "hard coded" file path.
readFromCsv(filePath='home/vm/user/test.csv')
My Python project are opened via the console like:
python myproject.py config.cfg
and depending on the config file, there are other paths to other csv files
with open(sys.argv[1], 'r') as input_file:
filePath = input_file.readline().rstrip("\n")
Is there a way to parse the file path to a variable that the following function call work?
readFromCsv(filePath)
Thanks a lot!

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

Script executing fine, but not writing to any files in specified directory

I am trying to write a script that will iterate through a specified directory, and write to any .txt files with a new string.
Edited after reading Lev Levitsky's explanation
import os
x = raw_input("Enter the directory path here: ")
def rootdir(x):
for dirpaths, dirnames, files in os.walk(x):
for filename in files:
try:
with open(os.paths.join(dirpaths, filename 'a')) as f:
f.write("newline")
except:
print "Directory empty or unable to open file"
return x
rootdir(x)
The script executes, however I get my "Directory empty or unable to open file" exception.
Thanks in advance for any input.
If this is the whole script, then your function is never called, so no wonder nothing happens to the files. You need to actually call the function with the user-provided path:
rootdir(x)
Other issues I see with your code:
The function will erase the text file's content and replace it with "newline". That is because you open the file in write mode. Consider using append mode ('a') instead.
There is no os.dirpaths. You need os.path.join(dirpaths, filename). Also, 'w' is an argument to join, but it should be an argument to open. So in fact the files will be opened in read mode and with incorrect names, resulting in an error.
Finally, because of the return statement inside the loop body, the function will return after processing just one file, without touching the rest.

Categories

Resources