Determine file extension [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I tried to solve the following problem by creating a new file, then tried each one of these functions to get the file extension but all i got was errors.
What am I doing wrong?
"Examine the following three functions that take as argument a file name and return the extension of that file. For instance, if the file name is 'myfile.tar.gz' the returned value of the function should be 'gz'. If the file name has no extention, i.e. when the file name is just 'myfile', the function should return an empty string."
def get_extension1(filename):
return(filename.split(".")[-1])
def get_extension2(filename):
import os.path
return(os.path.splitext(filename)[1])
def get_extension3(filename):
return filename[filename.rfind('.'):][1:]**
Which of the these functions are doing exactly what they are supposed to do according to the description above?
a) get_extension1 and get_extension3
b) get_extension3 only
c) get_extension2 and get_extension3
d) All of them

get_extension1(filename) will return the file name if filename does not contain .
get_extension3(filename) will raise an error because of ** at the end:
SyntaxError: invalid syntax
get_extension1 shoud be:
def get_extension1(filename):
output = filename.split(".")
return output[-1] if len(output)>1 else ''

Try it and find out:
get_extension1("myfile.ext")
Out[60]: 'ext'
get_extension1("myfile")
Out[61]: 'myfile' # wrong
get_extension2("myfile.ext")
Out[62]: '.ext'
get_extension2("myfile")
Out[63]: ''
get_extension3("myfile.ext")
Out[64]: 'ext'
get_extension3("myfile")
Out[65]: ''
Edit: it sounds like the AttributeErrors are because you are passing something other than a string for filename. If filename is a string they run just fine, but get_extension1 fails if the filename has no extension.

Related

I am trying to use the list I made in my getData function in my normalise function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
import string
def getData(filename):
with open(filename,'r') as f:
lines=[line.rstrip() for line in f]
lines=[x.lower() for x in lines]
return lines
filename="bibleSentences.txt"
getData(filename)
def normalize():
lowercase_lines=[x.lower() for x in lines]
return lowercase_lines
normalize(filename)
normalize()
I am trying to use the list I made in my getData function in my normalize function but I am getting an error saying that "lines is not defined" in the normalize function.
I am wondering how to call the function the right way so that I can avoid the error.
I guess you meant:
filename="bibleSentences.txt"
def normalize(filename):
lowercase_lines=[x.lower() for x in getData(filename)]
return lowercase_lines
normalize(filename)
What went wrong
When python returned the line variable to you, you didn’t assign it to anything, and therefore just lost it. A better way of doing it would be below.
Improved Code
filename="bibleSentences.txt"
lines = getData(filename)
def normalize():
lowercase_lines=[x.lower() for x in lines]
return lowercase_lines
lowercase_lines = normalize(lines)

Python problem can't run module and output problem [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I write code which will output some data file, but I got error and have no idea what is wrong already looking for 2 hours (you know how is it :) )
import binascii
import sys
import time
url12 = "my win dir for file"
def toHex(s):
1st = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
1st.append(hv)
return reduce(lambda x,y:x+y, 1st)
url = toHex(url12)
.......etc.
debug output:
Traceback (most recent call last):
File "C:\Users\RED\Desktop\builder\builderUpdate.py", line 22, in <module>
url = toHex(url12)
File "C:\Users\RED\Desktop\builder\builderUpdate.py", line 20, in toHex
return reduce(lambda x,y:x+y, lst)
NameError: name 'reduce' is not defined
In Python 2, reduce was a built-in function. In Python 3, you have to import it from functools
That's why you're getting an error
Also, the empty list in your function can't begin with a number otherwise you get a syntax error. It can contain numbers but should start with an underscore or a letter

Python match pattern to rename file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have couple of files with like this, llm_rc_v3212.xml, llm_ds_v3232.xml.
Names can be anything. however, common parameter would be_v3212. I want to match this number and replace it (ideally renaming the file).
How can i match this pattern with regex? I am trying to use re.sub, but not able to figure yet.
any help would be appreciated.
Here is a working example. Take into account that depending on other filenames the regex might need to be changed.
import re
FILENAME_VERSION_REGEX = re.compile(r'_v(\d)+')
def rename(filename, replacement):
full_replacement = r'_v{}'.format(replacement)
new_filename = FILENAME_VERSION_REGEX.sub(full_replacement, filename)
return new_filename
Tested with the filenames you gave:
>>> rename('llm_rc_v3212.xml', 1)
'llm_rc_v1.xml'
>>> rename('llm_ds_v3232.xml', 2)
'llm_ds_v2.xml'
>>> rename('llm_v232_uc.xml', 3)
'llm_v3_uc.xml'

parameter passing to python3.x script from commandline [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i am very new to python.
i would like to write a script where if i didn't pass any value to an argument, it should ask value for that argument. if passed, it should pick that value and continue.passing these values are from command line.
i tried below code and python is throwing error saying variable is not initialized.
if (fileName == None)
fileName == "C:\\filename"
print(fileName)
command line call for executing the script:- script.py "C:\filename"
Stack trace :-
if(NO_ERROR == None)
^
SyntaxError: invalid syntax
You are missing a colon at the end of the if statement
if (fileName == None):
fileName = "C:\\filename"
print(fileName)
sys module provides lots of options to play with command line arguments.
below example might be helpful to you.
import sys
#storing the argument in string
st=" ".join(sys.argv)
#splitting the list to get the file name and storing it in list
var=st.split('=')
if len(sys.argv)<2:
print "Enter Argument\n"
else:
print 'Argument found'
print var[1]

How to make my python script accepts multiple positional arguments? [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 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.

Categories