Trying to transfer a file name to a different function - python

I am writing code for class and I'm stuck on just one problem. I'm supposed to use the main function to call to a different function called 'file2list' which will take the file (that I brought from main) and convert it to a list. I have everything needed to create the list, I just can't get the file to run. (also I'm new to programming, so there can also be some silly errors)
This is in my main function
#Call file2list
vt=file2list('vt_municipalities.txt')
nh=file2list('nh_municipalities.txt')
And then this is what my file2list function looks like
def file2list(muni_file):
#Create lists
muni_list=[]
#Open files
file=open('muni_file','r')
Basically, how can I bring the .txt file down to file2list? I get the error that muni_file doesn't exist. Thanks!

Your error is that you are trying to open the file with the name muni_file, as you surrounded it with ', making it a string. To reference the variable that was passed into the function, remove the quotation marks (') surrounding muni_file.
The file=open line should look something like this:
file=open(muni_file,'r')

you are passing to open() a string that contains 'muni_file' as value, to use the parameter that you recieve, you should pass without ' '

Related

Python - Import formatted lines as indexed list objects

I am writing a minor OP5 plugin in Python 2.7 (version is out of my hands) that iterates over a multidimensional list that verifies fallback zip downloads have gone as they should.
Up until now I have put each host with their IP address in a multidimensional list looking like (cut short for brevity):
fallback = [
["host1", "192.168.1.3"],
["host2", "192.168.15.59"]
]
...and so on.
This lets me iterate through fallback[i] and use that along with fallback[i][1] for the IP address, the rest of the script uses both of these informations for various tasks and string manipulations. The script as it is now is mechanically sound but relies on availability of these indexes.
There is however a hidden file (.fallbackinfo) containing the same information for another script but it is written for perl, same as the script that uses that file as a source.
The file looks like this:
#hosts = (
["host1", "192.168.1.3", "type of firmware", "subfolder"],
["host2", "192.168.15.59", "type of firmware", "subfolder"],
);
I wish to import this into an iterable multidimensional list in my Python script, but am getting incredibly stuck.
My current attempt is the closest I have gotten:
with open("/home/runninguser/.fallbackinfo") as f:
lines = []
for line in f:
lines.append(line.rstrip().strip())
fallback = lines[1:len(lines)-1]
This has successfully made the list look as I want it, but all lines get imported as str objects. I have attempted to use list() to force the object to become a list but most of the time, that makes each character in the lines to become a list object instead. The network in question is cut off from internet access so I have to rely on built-in modules. My interpretation is that since it is formatted as a list, it should somehow be able to be interpreted as a list.
Can this be done at all, and if so, how?
You can use the json package (built-in) to achieve this:
import json
with open("/home/runninguser/.fallbackinfo") as f:
# For each line
for line in f:
# If the line starts with a bracket
if line.strip()[0] == "[":
# Print the line after removing spaces in front and the comma in the back
# and converting it into a list
print(json.loads(line.strip().rstrip(",")))
If you now use the type() function, you will see the list-formatted strings are now <class 'list'>

How to call a file name when I want to use a small portion of the name?

I am trying for my code to pull a file when only a portion of the file name changes.
Example: I want to pull the file named JEFF_1234.csv where 1234 is an input from a GUI window.
The reason for the file name to have this structure is I want to have one main database that has multiple files for a specific part number. So if the user inputs a part number of 1234 and that will point to 4 files. JEFF_1234.csv, SAM_1234.csv, FRED_1234.csv and JACK_1234.csv.
What you need is a way to update a template with some dynamic value.
A neat way to do this is to define a template string using curly brackets as place-holders for the content that will be generated at runtime.
jefffile_template = "JEFF_{t}.csv"
Then, once you've assigned a value to the unknown pointer, you can convert your template into an appropriate string:
jeff_filename = jefffile_template.format(t="1234")
Which will store the value of JEFF_1234.csv into the variable jeff_filename for usage later in your program.
There are other similar ways of calling formatting functions, but using this by name style is my preferred method.
...and in case you're wondering, yes, this was still valid in 2.7.

Editing every 3rd line of file in vim

I was making a templated list of methods in vim for a python project. I added lines between each method and wanted to add a pass to each method for now-until I implement the method, this will still be interpretable python code. In vim I know how to edit spatially contiguous lines of a file using :10,17s/<search regex>/<substitute>/ but after doing my edits to add empty lines between methods, I needed to insert the a pass every 3rd line. The way I found to do this used pipes and & via:
:10s/<search regex>/<substitute>|13&|16& etc. I had maybe 15 of the ampersands chained together to get this to work. Is there a more succint way to get this behaviour in vim?
To address comment, here is a minimal example, in the file myfile.py I have:
def _fun1(self):
def _fun2(self):
def _fun3(self):
def _fun4(self):
...etc
On the 2nd line, the 5th line, the 8th line, etc. I want to insert pass (w/4 spaces before to keep consistent spacings), /i have this up to _fun15(self): so would like to get the behavior w/o 14 |lineNo&s chained together. Perhaps an incrementing feature w/a variable for the line numbers or some other code that creates the behavior.
Here is one possible way:
:g/def _fun/normal! opass
On each line matching def _fun…
open a new line below…
and insert pass.
If you want to have one single line between each stub:
:g/def _fun/normal! opass^OJ^Ox
On each line matching def _fun…
open a new line below…
insert pass…
leave insert mode for a single command…
join the line below with the current line…
leave insert mode for a single command…
and remove that pesky <Space>.
Record a macro
qajopass<Esc>jq
Now execute it by running #a (next time you can use ##).
As #midor said it can be then used with :g command in form of:
:g/def _fun\d\+/norm #a
To execute this macro on all matching lines.
To put 'pass' with indentation below each function definition I would use:
:g/^def/put =' pass'
^ ........... begining of each line
put ......... puts contents bellow
To squeeze blank lines:
:g/^$/,/./-1j
a global command the gets from each empty line ^$
until next non-empty line minus one, performs a join command

Can I use asterisk * in config file variable name?

I am using Config Parser to specify a list of variables, and the values for those variables are then pulled from a larger file. The variables/lines in the larger file all look like this:
callCount.1.cell=2
callCount.2.cell=10
callCount.3.cell=12
Rather than listing all these variables specifically, would I be able to use an '*' as a wildcard character, in place of the number, like this:
[variablesToPull]
callCount.*.cell
I can't change the formatting of the larger file I'm pulling values from, and I don't always know what the numbers that are apart of the variables will be.
EDIT: I'm using Python 2.7 to do all my Config Parsing
After looking around for a while I don't think it's possible. I ended up using just the first part of the desired variable name in the config file
[variablesToPull]
callCount
Then I created a dictionary from the file I was storing the full list of variable names and values in (All the following code is for Python 2.7, it probably works for Python 3, but might need some syntax changes)
f = open(variable_names_and_values_file, 'r')
dict_of_vars= {}
for line in f:
k, v = line.strip().split('=')
dict_of_vars[k.strip()] = v.strip()
f.close()
Then I looped over this dictionary and created a new list of the specific variables to pull (like callCount.1.cell, callCount.2.cell, ect...)
new_variables= []
for var in partial_variable_names_from_config_file:
for data in dict_of_vars:
if var in data:
new_variables.append(data)
Initially I didn't want to do so much looping for fear of performance decrease (my file of variables has like 10000 lines), but it doesn't seem to have slowed down my script by a noticeable amount.
Hope this helps someone out there

Assigning variable for dynamic filename in Python

I am new to python scripting and am required to build a script for WebLogic Server. The requirement is to use a file (type .rpd) from assigned location for deployment. The file type would remain same throughout, however, the file name would change.
Given this condition, I tried the below methods on assigning file to the variable. Both the below methods are not working.
rpdfile = "*.rpd"
rpdlocation = "/u02/RPD_Upload/"+rpdfile+
or
rpdlocation = "/u02/RPD_Upload/*.rpd
I get invalid syntax error while running the python. Experts please help me understand on assigning such variables.
For your first method, you are not appending correctly. You have an extra '+' at the end of the line. It should look like this:
rpdfile = "*.rpd"
rpdlocation = "/u02/RPD_Upload/" + rpdfile
For your second method, you are not closing the double-quote. See below:
rpdlocation = "/u02/RPD_Upload/*.rpd"

Categories