How to input command into python script - python

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(' ', '_')))

Related

Python: how to save text + element from the list to the txt file

I'm learning Python and I'm trying to combine saving text + specific element from the list to a txt file.
I managed to get the text out and it looks like this:
Project name:
Main worker:
Project name:
Main worker:
and this is fine but I would like to add workers and projects that are in the lists to look like this:
Project name: Microsoft
Main tester: Michael Scott
Project name: Amazon
Main tester: Dwight Schrute
And I'm not sure how to add that, this is what I got so far:
class Worker:
def __init__(self, name, lastname):
self.name = name
self.lastname = lastname
def name_lastname(self):
print(self.name, self.name)
class Project:
def __init__(self, name, worker):
self.name = name
self.worker = worker
workers = []
projects = []
name1 = input("Enter the name: ")
lastname1 = input("Enter the last name: ")
workers.append(name1 + ' ' + lastname1)
name2 = input("Enter the name: ")
lastname2 = input("Enter the last name: ")
workers.append(name2 + ' ' + lastname2)
projectname1 = input("Enter the name of the project: ")
projectname2 = input("Enter the name of the project: ")
projects.append(projectname1)
projects.append(projectname2)
print(workers)
print(projects)
file = open("projects.txt","w")
file.write("Project name: \n")
file.write("Main worker: \n")
file.write("Project name: \n")
file.write("Main worker: \n")
file.close()
If I understood you correctly, just writing the names and projects like you did with the headers (e.g. "Project name:") would be sufficient. For example:
file.write("Project name: \n")
file.write(projects[0] + "\n")
file.write("Main worker: \n")
file.write(workers[0] + "\n")
file.write("Project name: \n")
file.write(projects[1] + "\n")
file.write("Main worker: \n")
file.write(workers[1] + "\n")
file.close()
For lists, you can access the first element with a list[0], the second one with list[1] and so on. This is however a fairly manual approach and you could use a loop here to iterate over the list entries if you have more entries later on.
I not sure about your input and output data but I hope I understand it correct. And because you are a Python learner I took the liberty to introduce some other Python techniques to make the solution more Pythonic and less error prone.
The full example
#!/usr/bin/env python3
import pathlib
# example data (assuming both lists with same length)
all_workers = ['John Doe', 'Jenny Boe']
all_projects = ['Project Alpha', 'Project Beta']
# file path
projects_file_path = pathlib.Path('projects.txt')
# open the file
with projects_file_path.open('w') as file_handle:
# iterate over your lists side by side
for worker, project in all_workers, all_projects:
file_handle.write(f'Project name:\n{project}\n')
file_handle.write(f'Main worker:\n{worker}\n')
# let's look what is in the file
with projects_file_path.open('r') as file_handle:
print(file_handle.read())
The resulting projects.txt file look like this. Is this what you wanted?
Project name:
Jenny Boe
Main worker:
John Doe
Project name:
Project Beta
Main worker:
Project Alpha
Step-by-step explained
I removed the two classes from your example code because I couldn't see an advantage of them. I also removed the input() part and hard coded some sample data. Hope this is OK that way?
# example data (assuming both lists with same length)
all_workers = ['John Doe', 'Jenny Boe']
all_projects = ['Project Alpha', 'Project Beta']
To interact with files and the filesystem it is recommended to use Pythons pathlib package. The with block in the code make sure that the file is closed automatically when the block ends.
import pathlib
projects_file_path = pathlib.Path('projects.txt')
# open the file
with projects_file_path.open('w') as file_handle:
# write...
I think the for-loop is self explaining. It's advantage is it prevents you from write repetitiv code.
I constructed the string written into the file with the f-string like this.
file_handle.write(f'Project name:\n{project}\n')
But you could also use the old way with format().
file_handle.write('Project name:\n{}\n'.format(project))

Taking user input to create text file names with prewritten name and user input

Hi I'm trying to create a couple text files with a prewritten tag along with a given user input.
For Ex. I need 5 file names with a prewritten tag and the input
Cat100.txt
Where cat is predetermined and the number 100 is the user input.
I have this but I can't find out how to add a prewritten tag along with the user input.
filename = input ("filename: ");
with open (filename, "w") as f:
Thank you!
Updated per comment clarifications:
import os
folderpath = ".\\test_folder\\"
prewritten_tag = "User wrote: " # example
user_filename = input("filename: ")
full_filename = prewritten_tag + user_filename
fullpath = os.join(folderpath,full_filename) # gets absolute path
with open(fullpath, "w") as f:
user_input = input()
full_txt = stuff + input() + otherstuff
f.write(full_txt)

Replace Variables in a .docx file with user inputted variables

I have a project that I am working on. I have a .docx template that I've created.
Within there, I have multiple variables across the whole document that need to be replaced with user-imputed information, (some variables are replaces more than once within the doc).
I have this code that I modified from previous .txt files that I have worked with. I am not able to take the .docx file, edit the vars with user imputed info and create a new file that I can share/print. Any help would be appreciated.
I have attempted to try to use python-docx but alas, I have not fully understood the concept and make it work.
Sample code follows:
from __future__ import with_statement
import fileinput
#def terms and ask user for imput
def loaDocOne():
words = ["[clientName]","[addressLine1]","[addressLine2]","[todaysDate]","[fileNum]","[originalClient]","[refNum]","[currentBal]","]
clientName = input('Enter Clients name: ')
addressLine1 = input('Enter Clients Address Line 1: ')
addressLine2 = input('Enter Clients Address Line 2: ')
todaysDate = input('Enter Todays Date: ')
fileNum = input('Enter File Number: ')
originalClient = input('Enter Original Client: ')
refNum = input('Enter Original Refrence Number: ')
#open file
def replaceFunc():
with open ('template.docx') as f:
for line in f:
line = line.replace("[clientName]",clientName)
line = line.replace("[addressLine1]",addressLine1 )
line = line.replace("[addressLine2]",addressLine2 )
line = line.replace("[todaysDate]",todaysDate)
line = line.replace("[fileNum]",fileNum )
line = line.replace("[originalClient]", originalClient)
line = line.replace("[refNum]",refNum )
#Find out if everything looks good to continue
def goOn():
doYouWantToContinue = input('Does Everything Look Correct? yes/no: ')
if doYouWantToContinue == 'yes':
replaceFunc()
else:
loaDocOne()
loaDocOne()
goOn()
replaceFunc()
Also, Is there a way to take the outputted file and make it 'document_name_'fileNum'' with the user provided file number?
Using the python-docx module is the easiest way to proceed. The structure of a document opened using this module is documented here, and I think it's pretty easy to wrap your head around.
This code opens a document, then for each of it's paragraphs it replaces the existing text with the replaced text, using the str.replace function that automatically replaces all occurrences of some string.
from docx import Document
doc = Document('document.docx')
replacements = {
'%replace_me_1%': 'New text 1',
'%replace_me_2%': 'New text 2'
}
for paragraph in doc.paragraphs:
for key in replacements:
paragraph.text = paragraph.text.replace(key, replacements[key])
doc.save('document.docx')
Saving the file with a new name should be quite easy:
file_suffix = input()
doc.save('document_' + file_suffix + '.docx')

CSV rewriter keeps creating new headers

My code is creating the same headers each time, I want it to create one and append the data to a CSV without creating a new header.
What it looks like in the CSV
What I want it to look like
import csv
with open("Details.csv","a+") as Details:
w=csv.writer(Details,delimiter=",")
headers1=["Name","Age","Year Group"]
line=Details.readlines()
if line!=["Name","Age","Year Group"]:
w.writerow(headers1)
print("Welcome User, to my Topics Quiz!\n-------------------------------
--------\nYou can choose from 3 different topics:\n • History\n •
Music\n • Computer Science\n---------------------------------------")
print("Before we start, we need to register an account.")
User=input("Enter your name:\n")
Age=input("Enter your age:\n")
Year=input("Enter your year group:\n")
details=[User,Age,Year]
w.writerow(details)
Details.close()
with open("UserPass.csv","a+") as Userpass:
w=csv.writer(Userpass,delimiter=",")
headers2=["Username","Password"]
if headers2 not in Userpass:
w.writerow(headers2)
NewUser=(User[:3]+Age)
print("Great! Your username is set to: {}".format(NewUser))
Pass=input("Enter a password for your account:\n")
userpass=[NewUser,Pass]
w.writerow(userpass)
Userpass.close()
Any help is greatly appreciated.
You are opening file in appending mode (https://docs.python.org/3/library/functions.html#open), so this line=Details.readlines() will always be empty line and your headers will be written every time (code will always get into if).
It is similar with other file. So I suggest you first check if file exist, and if not create it and add headers, and remove headers part from with:
import csv
import os.path
if not os.path.isfile("Details.csv"):
with open("Details.csv", "a+") as Details:
w = csv.writer(Details, delimiter=",")
headers1 = ["Name", "Age", "Year Group"]
w.writerow(headers1)
Details.close()
if not os.path.isfile("UserPass.csv"):
with open("UserPass.csv", "a+") as Userpass:
w = csv.writer(Userpass, delimiter=",")
headers2 = ["Username", "Password"]
w.writerow(headers2)
Userpass.close()
with open("Details.csv", "a+") as Details:
w = csv.writer(Details, delimiter=",")
print("Welcome User, to my Topics Quiz!\n-------------------------------"
"--------\nYou can choose from 3 different topics:\n • History\n • "
"Music\n • Computer Science\n---------------------------------------")
print("Before we start, we need to register an account.")
User = input("Enter your name:\n")
Age = input("Enter your age:\n")
Year = input("Enter your year group:\n")
details = [User, Age, Year]
w.writerow(details)
Details.close()
with open("UserPass.csv", "a+") as Userpass:
w = csv.writer(Userpass, delimiter=",")
NewUser = (User[:3] + Age)
print("Great! Your username is set to: {}".format(NewUser))
Pass = input("Enter a password for your account:\n")
userpass = [NewUser, Pass]
w.writerow(userpass)
Userpass.close()
There are different problems in your code:
1) Empty line between lines with data in csv file, it happens because of the nonbinary type of opening and can be fixed by adding that arg in open function:
w=csv.writer(Details,delimiter=",",lineterminator='\n')
2) In your case Details.readlines() method was returning [], because of the a+ type of opening, it's supposed to add lines in the end of file, so pointer is in the end already and we need to return it at the beginning by using that code:
line=Details.seek(0)
3) Also, we need only first line, so just use readline() method. And after all, your condition should look that way, because of the return type and the fact that there's \n in the end of every line:
if line!="Name,Age,Year Group\n":
And the full code of that part. Let me know if it works well for you:
w=csv.writer(Details,delimiter=",",lineterminator='\n')
headers1=["Name","Age","Year Group"]
line=Details.seek(0)
line=Details.readlines()[0]
print(line)
if line!="Name,Age,Year Group\n":
w.writerow(headers1)
I don't understand everything your code is trying to accomplish, but the following will add a row to the Details.csv without creating any new headers:
import csv
import os
csv_fileheader = "Name", "Age", "Year Group"
csv_filename = "Details.csv"
print("Welcome User, to my Topics Quiz!\n"
"---------------------------------------\n"
"You can choose from 3 different topics:\n"
" • History\n • Music\n • Computer Science\n"
"---------------------------------------")
print("Before we start, we need to register an account.")
user = input("Enter your name:\n")
age = input("Enter your age:\n")
year = input("Enter your year group:\n")
if not os.path.isfile(csv_filename): # Create file if it doesn't exist.
with open(csv_filename, "w", newline='') as csv_file:
csv.writer(csv_file).writerow(csv_fileheader) # Put header row in it.
with open(csv_filename, "a+", newline='') as details2:
writer = csv.writer(details2, delimiter=",")
writer.writerow((user, age, year))
You should consider following the PEP 8 - Style Guide for Python Code recommendations as it will make your code easier for both you and others to read.

create user input directory name in python

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)

Categories