How to pass a path into a variable (Python) - 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!

Related

How to edit file outside Python directory?

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()

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.

Python Error:CSV File Error, Read/Print CSV file

I am getting this error when trying to print the contents of a CSV file in Python.
Traceback (most recent call last):
File "/Users/cassandracampbell/Library/Preferences/PyCharmCE2018.2/scratches/Player.py", line 5, in
with open('player.csv') as csvfile:
FileNotFoundError: [Errno 2] No such file or directory: 'player.csv'
Get the exact file path to the csv, if you are on a windows get the entire folder path and then the name, and then do:
with open(r'C:\users\path\players.csv') as csvfile:
If you're using a windows and the exact path, easiest to put the r before the path like I did because it is a literal which will allow the string to be interpreted and the path to be found.
You must put player.csv to the same location with your script Player.py
Example like your code, both files should be here: /Users/cassandracampbell/Library/Preferences/PyCharmCE2018.2/scratches/
Or you can put the specific directory of player.csv,
Ex:
with open("/Users/cassandracampbell/Library/Preferences/PyCharmCE2018.2/scratches/player.csv") as csvfile:
...
Check that you have the file in question in same directory as your .py file you're working on. If that doesn't work you might want to use the full path to the file:
with open ('/Users/cassandracampbell/Library/Preferences/PyCharmCE2018.2/scratches/player.CSV') as csvfile:
And you should try to check the name of the file too should be case sensitive otherwise, let's say you have Player.csv then don't try to open player.csv all lower case won't work!
Plus I don't know what you're trying to do with your CSV file, just print the raw content? You might like using pandas.

Creating a .py file rather than .txt file using open(file_name, "w+")

I have a text file that I created using
open(new_file_name_string,"w+")
I want to know if/how I can use the open function (or any other python function) to create a python (.py) file instead of a text (.txt) file. For instance, can I use a different argument than "w+" to make open generate a python file?
If there is nothing like this available, is there a python function that can convert my .txt file into a .py file?
if you mean that you want to change the extension, just change the filename. If your previous filename is just filename or filename.txt just change it to filename.py

Python cannot see csv file

I went through couple answers on forum already but without any success.
I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs:
file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'
My code:
import csv
file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". Still doesn't work.
Completely new to Linux and just can't find why this isn't working.
Each reply appreciated!
You should'nt use '~' to specify the path of your directory but the full path instead. E.g. :
import csv
file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)
If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv'). E. g. :
import csv
file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)
The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion
Try using the full file path, something like this:
file = open("/home/[username]/Desktop/xyz/city.csv", "rb")
Usually ~ does not expand properly. I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix.

Categories

Resources