How to make my python script accepts multiple positional arguments? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Suppose that I would like my python program to accept 2 positional arguments:
1. The path to an input file
2.The path to a word dictionary, which is also a txt file.
Can anyone teach me how to go about doing that?

import sys
print('Name of the script: {0}'.format(sys.argv[0]))
if len(sys.argv) == 3:
inputfile_path = sys.argv[1]
dictionary_path = sys.argv[2]
print('First parameter: {0}'.format(inputfile_path))
print('Second parameter: {0}'.format(dictionary_path))
https://docs.python.org/2/library/sys.html

Your question is a bit vague so I'm just going to answer what I think you meant.
I'll assume that you have a function as such:
def function(string1, string2):
''' string 1 and string2 are paths to an input file and a dictionary respectively'''
Now in general to read a file you use:
file1 = open(string1,'r')
# After opening the file you loop over lines to do what you need to.
for line in file:
# Do what you need to
I'm not sure what you want to do with the input file so I'm going to leave it at that.
To load a dictionary from a string we use the eval() function. It actually runs a string. Now each line in the dictionary stored as a text file is a string so all you have to do is loop through the entire file (using the for line in file method from before) and run eval to get back a dictionary.
For example try this simple code:
#assume string2 is what you get back from the looping
string2 = str({'jack': 4098, 'sape': 4139})
dic = eval(string2)
print dic
Hopefully I've pointed you in the right direction. Since I'm not sure what exactly you need to do, I can't really help you more.

Related

sorting and printing multiple lines in a prompted file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Here is my existing code:
filename = input("Enter file name (with extension) to read: ")
if filename == 'x':
exit()
else:
c = open(filename, "r")
print("\nThe file,", filename, "opened successfully!")
print("The file", filename)
print(c.readlines())
c.close()
My output is the file I input, which is great! But my problem is that I just need to figure out how to print the list in sorted order. Since the list is generated by the user input, I've not had experience with sorting functions, would I sort the c.readlines directly?
Programming is all about decomposition, breaking large problems into smaller pieces. There are several distinct tasks in your program: prompt the user for a file name, open that file, sort the lines, and print them. You've already got a handle on the first two, so cast those out of your mind now and focus on the last two. Whether a file was hardcoded and inputted by the user makes no difference once you've got it open.
To sort a list you have to primary options: call l.sort() to sort it in place, or call sorted(l) to return a sorted copy without modifying the original. Let's use the second one and loop over the result of sorted():
for line in sorted(c.readlines()):
print(line)
The call to readlines() is optional. You can also loop over the file directly, which is shorthand for looping over the lines.
for line in sorted(c):
print(line)
(I prefer to call readlines() explicitly, myself. It's a stylistic choice; either way is acceptable.)

Why is reading from a file not working after using a function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
My code is supposed to find the occurrence of words in a text. For some reason, after using this function, the reading method from this specific textwon't work(empty lists for .readlines() method and nothing for .read()). The code is:
def counter(new):
words = dict()
lines=new.readlines()
for line in lines:
text=line.split()
for word in text:
if word not in words:
words[word]=1
else: words[word]+=1
return [tuple(x) for x in words.items()]
I haven't found any mistake that can cause this.
I am assuming new is the result of calling open(..), which should be a file handle that you are passing into the function. Calling readlines() is exhausting it, so trying to read from the file using the same handle won't work. Either open a new handle, or you can call new.seek(0) (better option than opening a completely new handle - although there are some cases where the same handle will be returned again, but lets not dive too deep into that here) to move the index to the beginning of the file.

Trying to make a function that copies the content of one file and writes it to another [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a question that states
Write a function fcopy() that takes as input two file names (as strings) and copies the content of the first file into the second.
and I want to know how to go about solving this.
My first file is named example, and the second file is named output, both text files are in .txt format, and the path to them are
"C:\Users\HOME\Desktop\Introduction to Computing\Lab\assignments\example.txt"
and "C:\Users\HOME\Desktop\Introduction to Computing\Lab\assignments\output.txt"
You are not to ask StackOverflow to do your homework for you. Feeling generous though...
First of all, read this: https://docs.python.org/3.3/library/shutil.html It's the Python 3 docs for the shutil module. It will give high-level functions for reading/writing files (I/O).
from shutil import copyfile
copyfile(locationOfSource, locationOfDestination)
An important thing to note is that "\" (back-slash) signifies non-literal text, so "\n" means new line, NOT just "\n". This is rarely mentioned and had me stumped when I first learnt escape characters. To do the back-slash that you want within a string, you MUST use "\" instead of "\".
The commenters below your answer are correct, please read the information given to you by StackOverflow about asking questions. Also, welcome to the site.
If you really need to, you could write a simple wrapper function to accomplish this:
def copy_file(orig_file_name, copy_file_name):
with open(orig_file_name, 'r') as orig_file, open(copy_file_name, 'w+') as cpy_file:
orig_file = orig_file.read()
cpy_file.write(orig_file)
But as #Frogboxe has already said, the correct way to copy a file is to used the shutil library:
import shutil
shutil.copy(target_file, copy_file)

python 3 Acess file and check number of time phrase comes up [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to check a TSV of results and want to see how many times F and S come up (for failure or success) however I'm not sure how to doing this counting, or how to having it search the file
I've come across something that is sort of what I'm looking for: Python Program how to count number of times the letter c shows up
def countletter(S, F):
count = 0
for x in S:
if x.lower() == F.lower():
count += 1
return count
print (countletter("abcdefFf","F"))
But it isn't perfect and I'm not sure how to make it search the file.
Assuming that the count result applies to the whole file you can use a collections.Counter:
from collections import Counter
with open('input.tsv') as infile:
counts = Counter(infile.read())
for c in 'SF':
print '{}: {}'.format(c, counts.get(c))
This has the advantage of allowing you to obtain counts of any character (not just "S" and "F") with one pass of the file.
You could also just use str.count() for a specific character (or a string), but if you need counts more than one character you'll find a Counter more convenient and probably faster too.
You need to pass the file contents to your countletter function.
with open("FILE_TO_OPEN_AND_READ.txt") as f:
data = f.read()
print (countletter(data,"F"))
This opens and reads the file into data. For this example, I'm assuming your file is relatively small. Then data is passed into countletter as the first parameter, instead of a hardcoded string ("abcdefFf" in your example).
One note about your code, you are missing a closing parenthesis in your print statement. I've added that in my example above.

Python function,issue with input file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have function written by a colleague working in same field. So I know I should write script to execute python code,but issue of how the format of the input bbfile looks like bothers me.As I see fidlines read all the content,correct?My may concern is bbfile(tab delimited in my case),should it have three columns one for freq,other for breal and third for bimag?
def bbcalfunc(bbfile,nfreqlst):
fid=file(bbfile,'r')
fidlines=fid.readlines()
#define the delimiter
if bbfile.find('.txt')>=0:
delimiter='\t'
elif bbfile.find('.csv')>=0:
delimiter=','
freq=[]
breal=[]
bimag=[]
for ii in range(1,len(fidlines)):
linestr=fidlines[ii]
linestr=linestr.rstrip()
linelst=linestr.split(delimiter)
if len(linelst)>2:
freq.append(float(linelst[0]))
breal.append(float(linelst[1]))
bimag.append(float(linelst[2]))
else:
pass
freq=np.array(freq)
breal=np.array(breal)
bimag=np.array(bimag)
nfreq=np.log10(np.array(nfreqlst))
brinterp=interpolate.splrep(freq,breal)
brep=1E3*interpolate.splev(nfreq, brinterp)
biinterp=interpolate.splrep(freq,bimag)
bip=1E3*interpolate.splev(nfreq, biinterp)
return brep,bip
The format of the input file depends on the extension that you use, a .txt file will be a Tab Separated Values (tsv) file while a .csv file will be a Comma Separated Values (csv) file (please note that this is not a general convention, it is something that was decided by that colleague of yours that wrote the function, or maybe it's a local convention).
Each line of the file is usually composed by three {tab,comma} separated values, i.e., frequency, real part and imaginary part of a complex value.
I said usually composed because the code silently discards all the
lines for which the element count is less than three.
There is something here and there that can be streamlined in the code,
but it's inessential.
Rather, to answer your question re closing the file, change the first part
of the function to
def bbcalfunc(bbfile,nfreqlst):
#define the delimiter
if bbfile.find('.txt')>=0:
delimiter='\t'
elif bbfile.find('.csv')>=0:
delimiter=','
# slurp the file
with file(bbfile,'r') as fid:
fidlines=fid.readlines()
...

Categories