I am trying to generate a python script that takes 3 input arguments and creates a directory whose name is a concatenation of the 3 arguments. The command i give is python new.py user1 32 male and I should get a directory name created as user1_32_male, but I am getting directory name as user_name + "" + age + "" + gender. Can someone please correct my code
#!/usr/bin/python
import pexpect
import numpy as np
#import matplotlib.pyplot as plt
#import pylab as p
from math import *
from sys import argv
import os.path
import numpy as np
import os, sys
#print "Hello, Python!"
script, user_name, age, gender = argv
dirname = user_name + "_" + age + "_" + gender
newpath = r'./dirname'
if not os.path.exists(newpath):
os.makedirs(newpath)
You put the expression you want to evaluate to the directory name you want in quotes, so it doesn't get evaluated. Try:
newpath = r'./' + user_name + "_" + age + "_" + gender
First of all, I noticed that you're importing things more than once. There's no reason to import os.path since it's included in os. The same goes with sys.
It's easier to use string substitution in cases like this. The tuple that comes after the % contains values that are substituted into the %s in the part before the %.
from sys import argv
import os.path
script, user_name, age, gender = argv
newpath = '%s_%s_%s' % (user_name, age, gender)
if not os.path.exists(newpath):
os.makedirs(newpath)
Related
When ever I run i try to add a column in pandas dataframe by iterating through a directory like this
import pandas as pd
import os
import sys
########generate file path
'getcwd: ', os.getcwd()
osfile, maindir =('__file__: ', __file__)
filename = os.path.basename(sys.argv[0])
inpath = maindir.replace(filename,"Excels")
outpath = maindir.replace(filename,"BulkFile.xlsx")
#########pandas script
def add_column():
for root, dirs, files in os.walk(inpath):
print(files)
for f in files:
path = os.path.join(root, f)
excelframe = pd.read_excel(path)
excelframe['full_name'] = excelframe['first_name'] + " " + excelframe['last_name']
dataframe = [excelframe]
compactframe = pd.concat(dataframe)
compactframe.to_excel(outpath)
it does nothing, no error codes or anything, it just does nothing.
But if I don't iterate through a directory and replace that script with this
import pandas as pd
import sys
import os
#####generate file path
osfile, maindir =('__file__: ', __file__)
filename = os.path.basename(sys.argv[0])
inpath = maindir.replace(filename,"BulkFile.xlsx")
outpath = maindir.replace(filename,"newfile.xlsx")
########pandas script
excelframe = pd.read_excel(inpath)
excelframe['full_name'] = excelframe['first_name'] + " " + excelframe['last_name']
dataframe = [excelframe]
compactframe = pd.concat(dataframe)
compactframe.to_excel(outpath)
It works just fine.
Does anybody know why this is or how to iterate through a directory and add columns to a dataframe?
You have defined the function add_column but you haven't ran it. Add the line add_column() to the end of your first script to execute.
In my path /volume1/xx/ are several files with this character A_test1.pdf, B_test2.pdf, ...I want to seperate the test1 part without path and .pdf.
Im newbie so I tried first with full name
but I got only the "*.pdf" as a text.
What is wrong with the path oder placeholder * ?
splitname = os.path.basename('/volume1/xx/*.pdf')
Edit
I got 2019-01-18_RG-Telekom[] from orign ReT_march - I want 2019-01-18_RG-Telekom_march (text after underlining) xx is a folder
here is the whole code:
#!/usr/bin/env python3
import datetime
import glob
import os
import os.path
SOURCE_PATH = '/volume1/xx'
TARGET_PATH = os.path.join(SOURCE_PATH, 'DMS')
def main():
today = datetime.date.today()
splitnames = [os.path.basename(fpath) for fpath in glob.glob("./xx/*.pdf")]
for prefix, name_part in [
('ReA', 'RG-Amazon'),
('GsA', 'GS-Amazon'),
('ReT', 'RG-Telekom'),
('NoE', 'Notiz-EDV'),
]:
filenames = glob.iglob(os.path.join(SOURCE_PATH, prefix + '*.pdf'))
for old_filename in filenames:
new_filename = os.path.join(TARGET_PATH, '{}_{}_{}.pdf'.format(today, name_part, splitnames))
os.rename(old_filename, new_filename)
if __name__ == '__main__':
main()
Use glob, os.path don't know how to process masks, but glob.glob works:
splitnames = [os.path.basename(fpath) for fpath in glob.glob("./**/*.txt")]
splitnames
Out:
['A_test1.pdf', 'B_test2.pdf']
Output of the glob:
glob.glob("./**/*.txt")
Out:
['./some_folder/A_test1.pdf', './another_folder/B_test2.pdf']
Apply os.path.basename to this list and extract basenames, as it shown above.
Edit
If xx in the path volume1/xx/ is just a folder name, not a mask, you should use following expression:
splitnames = [os.path.basename(fpath) for fpath in glob.glob("./xx/*.txt")]
because ./**/ is expression which masks a folder name and it's unnecessary that case.
import os
import random
path = os.listdir(r"file path here")
list = [os.listdir(r"life path here")]
print(len(path))
for i in range(len(path)):
full_path = (r"file path here" + path[i])
print(full_path)
print_random_items = random.randint(0, len(path[i]))
print(print_random_items)
So Hi I would like to know how I can print the name of the file associated with the value return to print(print_random_items)
ex: If the value is 15 I would like to print the 15th files name
First time asking a question here sorry if the format is wrong.
Don't bother with the random numbers. Just use random.choice:
random.choice(paths)
For example:
>>> import random
>>> paths = os.listdir('./exampledir')
>>> paths
['a.txt', 'b.txt', 'c.txt', 'd.txt', 'e.txt', 'f.txt']
>>> random.choice(paths)
'e.txt'
>>> random.choice(paths)
'c.txt'
Note: I see in your code that you are not familiar with python style iteration.
This
for i in range(len(path)):
full_path = (r"file path here" + path[i])
print(full_path)
is better written as
for partial_path in path:
full_path = r"file path here" + partial_path
print(full_path)
So rather than using range(len(path)) to get an index you can just iterate over path directly.
My current script is designed so that I am having to input 3 lines before I manage to open a certain website.
my code is named genius.py
I would like to know how to do it in one line
e.g.
genius.py eminem lose yourself
My current code is :
#!/usr/bin/python
import webbrowser
artist = raw_input("Enter artist name: ")
song = raw_input("Enter song name: ")
artist = artist.replace(" ", "-")
song = song.replace(" ", "-")
webbrowser.open("http://genius.com/"+artist+"-"+song+"-lyrics")
Command line arguments are in the sys.argv array.
import sys
artist = sys.argv[1]
song = sys.argv[2]
You'll need to quote names that contain spaces:
genius.py "the beatles" "a day in the life"
Otherwise there's no way to tell where the artist ends and the song begins.
You can use sys module;
import sys
print sys.argv
Or you can use more professional module like argparse
import webbrowser
webbrowser.open('http://genius.com/{0}-{1}-lyrics'.format(raw_input('Enter artist name: ').replace(' ', '_'), raw_input('Enter song name: ').replace(' ', '_')))
There are various python files in a directory and all these contain a function desciption() as follows :
def description():
desc = 'something'
return desc
Now I have main.py as follows :
def a():
pth = os.listdir('homedir/workspace')
for filename in pth :
exec "import " + filename
desc = eval(filename + '.desciption()')
print desc
Right now when I run python main.py, nothing happens. How do I print this desc when I run python main.py?
Thanks in advance!
Assuming the import worked, and that you have imported a module called filename in each iteration, then you could get the module by name, and call its descrpition() method:
import sys
mod = sys.modules[filename]
print mod.description()
But note that it may make more sense to print the module's pydocs:
print mod.__doc__
You didn't close quotes properly in this line:
pth = os.listdir('homedir/workspace)
Also you should not use eval here:
desc = eval(filename + '.desciption()')
and I assume you wanted to import by variable here:
exec "import " + filename
This is how it should look like:
def a():
import importlib
pth = os.listdir('homedir/workspace')
for filename in pth :
mdl = importlib.import_module(os.path.splitext(filename)[0])
desc = mdl.description()
print desc
see https://docs.python.org/2/library/importlib.html#importlib.import_module
https://docs.python.org/2/library/os.path.html#os.path.splitext
You missed the closing ' in the pth variable
You've referenced desc on the last line without declaring it first.
Start your function with desc = None
def a():
pth = os.listdir('homedir/workspace')
for filename in pth:
module_name = os.path.splitext(filename)[0]
exec "import " + module_name
desc = eval(module_name + '.description()')
print desc
make sure the main.py located at the same path with your modules. or add it to sys path by
import sys
sys.path.append(r"homedir/workspace")