How to write a file if the filename contains /? - python

I need to loop some stock tickers, and then output the files using the stock ticker:
without changing the filename
without the computer thinking that it's the wrong path because of the /
what's the solution? I tried:
for ticker in (['MSFT','BF/B','AAPL']):
file_name = "{}_prices.csv".format(ticker)
with open("/Users/my_mac/download/{}".format(file_name), "w") as f:
f.write('whatever')
the above code doesn't work because python thinks BF is the directory and B_prices.csv is the filename. I use chatgpt for suggestion, but it's not smart enough to give me a solution. It told me to:
use the os.path.join function to join the components of the file path
encode the file name using urllib.parse.quote() function, which will encode the special characters in the file name, including the slash /
replace the '/' character with an underscore ('_') or any other character that is a valid filename character.
and other stupid methods that doesn't work
I can't change the filename because it's the stock ticker, it has to be the same to run other code for something else after.
the robot suggested me to try the below also, but didn't work.
file_name = "{}_prices.csv".format(ticker)
file_path = "/Users/my_mac/download/{}".format(file_name)
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
with open(file_path, "w") as f:
f.write(response.text)
What's the solution?

Related

Create text file in folder

I'm trying to create a text file that is named using a variable in my program. Only problem is, I can't specify a directory when i'm naming it using a variable. (vac_postcode is the variable i'm using to name the file)
centrebypostcode = open(C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+")
centrebypostcode.write("\n")
centrebypostcode.write(vac_center)
centrebypostcode.close()
I'm using "a+" because I need the program to create the text file if it doesn't exist, but if it does, it just appends what I need it to, to the text file. (This is my understanding of the usage of "a+")
open(r'C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+" ') does not work either, unfortunately.
You have to keep the variable name outside the quoted string, change the line to
centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre" + "\\" + vac_postcode + ".txt", "a+")
Edited: the raw string literal cannot have the last backslash, so you need to concatenate that separately.
It looks like that quotation is wrong.
try with this
centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre\{}.txt".format(vac_postcode), "a+")
I just try to be more descriptive
filenames = ["my_file1","my_file2"]
for filename in filenames:
filename = f"C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode\{filename}.txt"
with open(filename, "a+") as fh:
fh.write("Hello world")

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"

Read all the text files in a folder and change a character in a string if it presents

I have a folder with csv formated documents with a .arw extension. Files are named as 1.arw, 2.arw, 3.arw ... etc.
I would like to write a code that reads all the files, checks and replaces the forwardslash / with a dash -. And finally creates new files with the replaced character.
The code I wrote as follows:
for i in range(1,6):
my_file=open("/path/"+str(i)+".arw", "r+")
str=my_file.read()
if "/" not in str:
print("There is no forwardslash")
else:
str_new = str.replace("/","-")
print(str_new)
f = open("/path/new"+str(i)+".arw", "w")
f.write(str_new)
my_file.close()
But I get an error saying:
'str' object is not callable.
How can I make it work for all the files in a folder? Apparently my for loop does not work.
The actual error is that you are replacing the built-in str with your own variable with the same name, then try to use the built-in str() after that.
Simply renaming the variable fixes the immediate problem, but you really want to refactor the code to avoid reading the entire file into memory.
import logging
import os
for i in range(1,6):
seen_slash = False
input_filename = "/path/"+str(i)+".arw"
output_filename = "/path/new"+str(i)+".arw"
with open(input_filename, "r+") as input, open(output_filename, "w") as output:
for line in input:
if not seen_slash and "/" in line:
seen_slash = True
line_new = line.replace("/","-")
print(line_new.rstrip('\n')) # don't duplicate newline
output.write(line_new)
if not seen_slash:
logging.warn("{0}: No slash found".format(input_filename))
os.unlink(output_filename)
Using logging instead of print for error messages helps because you keep standard output (the print output) separate from the diagnostics (the logging output). Notice also how the diagnostic message includes the name of the file we found the problem in.
Going back and deleting the output filename when you have examined the entire input file and not found any slashes is a mild wart, but should typically be more efficient.
This is how I would do it:
for i in range(1,6):
with open((str(i)+'.arw'), 'r') as f:
data = f.readlines()
for element in data:
element.replace('/', '-')
f.close()
with open((str(i)+'.arw'), 'w') as f:
for element in data:
f.write(element)
f.close()
this is assuming from your post that you know that you have 6 files
if you don't know how many files you have you can use the OS module to find the files in the directory.

How to execute Python code from file with a backslash character in it

I'm trying to run Python 3.3 code from a file with paths ("C:\Users\Documents\ect.") in it. When I try to run exec(commands), it returns this error:
tuple: ("(unicode error) 'unicodeescape' codec can't decode bytes in position ...
which I know is because of the single backslash character in the file paths, I know it works if it is backslashbackslash instead, but I don't know how to swap backslashbackslash for backslash. My code looks something like this:
filepath = HardDrive + "/Folder/" + UserName + "/file.txt"
file = open(filepath, 'r')
commands = file.read()
exec(commands)
The file simply has a command like this in it
os.remove("C:\Users\Documents\etc.")
The file path in the function in the file is returned automatically and I have no control over it.
Add a raw string r using str.replace to escape the filename inside the file:
with open("{}/Folder/{}/file.txt".format(HardDrive, UserName)) as f:
(exec(f.read().replace("C:\\",r"C:\\")))
Now the filename will look like 'C:\\Users\\Documents\\etc.'.
You also may need to remove that period:
exec(f.read().rstrip(".").replace("C:\\",r"C:\\"))
A simple
commands = commands.replace('\\', '/')
placed just before the exec(commands) would fix the problem if it's indeed all about the presence of backslashes (as it will turn each and every one of them into a forward slash).
Of course that's a problem if there are in the file also backslashes you want to keep as such (this simple code can't distinguish which ones you want to keep, which ones to replace!) but from your problem description this should not bother you in this case.
You can use r before your path, it will ignore all escape characters.
os.remove(r"C:\Users\Documents\etc.")
Like this.So,
file = open(r"filepath", 'r')
Beyond that, both Windows and Linux accepting / this for file paths. So you should use this. Not \, use this one /.
After your comment here;
file = open(r"{}".format(filepath), 'r')
Assume your variable is;
filepath = "c:\users\tom"
Put r before it and;
filepath = r"c:\users\tom"
Then use;
file = open(r"{}".format(filepath), 'r')
My final edit after you edited your question.
filepath = r"{}/Folder/{}/file.txt".format(HardDrive,UserName)
file = open(r"{}".format(filepath), 'r')

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