import os | |
def parent_directory(): | |
# Create a relative path to the parent | |
# of the current working directory | |
relative_parent = os.path.join(os.getcwd(), os.pardir) | |
# Return the absolute path of the parent directory | |
return os.path.abspath(relative_parent) | |
print(parent_directory()) |
Hi, could you explain line 6 code ? thank you!
Hi Ellieli78, I... think this is from a quiz on Coursera, line 6 uses the os.path.join method imported from the os module (line 1 import os) and as arguments it's taking another function of the os module to GET the Current Working Directory, and then another function from the os module to get the PARENT directory of the one we're currently in (not working directory, one step "up", as it were)
at least that's my 2cents, good code btw Rabeya
os.getcwd() - gets current directory and similar to "ls" on Linux or "dir in windows
os.pardir) - similar to ".."
os.path.join(os.getcwd(), os.pardir) the same as "ls" + ".." + "ls" in console
import os
def parent_directory():
Create a relative path to the parent
of the current working directory
os.chdir('..')
relative_parent = os.path.join('', os.getcwd())
Return the absolute path of the parent directory
return relative_parent
print(parent_directory())
My two cents
os.chdir('..')
relative_parent = os.path.join('', os.getcwd())
This doesn't work because you're merely changing to the parent directory then returning the current directory you're in.
Technically you're output is correct, but your method would be problematic to some people, especially if the prompt continued and assumed that you were in the starting directory.
Apparently os.pardir
is literally the same as '..'
.
import os
def parent_directory():
relative_parent = os.path.join(os.getcwd(), '..')
return os.path.abspath(relative_parent)
print(parent_directory())
More Linux-ious approach would be the following:
relative_parent = os.path.join(os.getcwd(), "..")
please help me out with this code
please i'm very confused on how to do it and it is an assignment I have to submit
menu = {
1: {"name": 'espresso',
"price": 1.99},
2: {"name": 'coffee',
"price": 2.50},
3: {"name": 'cake',
"price": 2.79},
4: {"name": 'soup',
"price": 4.50},
5: {"name": 'sandwich',
"price": 4.99}
}
def calculate_subtotal(order):
""" Calculates the subtotal of an order
[IMPLEMENT ME]
1. Add up the prices of all the items in the order and return the sum
Args:
order: list of dicts that contain an item name and price
Returns:
float = The sum of the prices of the items in the order
"""
print('Calculating bill subtotal...')
### WRITE SOLUTION HERE
raise NotImplementedError()
def calculate_tax(subtotal):
""" Calculates the tax of an order
[IMPLEMENT ME]
1. Multiply the subtotal by 15% and return the product rounded to two decimals.
Args:
subtotal: the price to get the tax of
Returns:
float - The tax required of a given subtotal, which is 15% rounded to two decimals.
"""
print('Calculating tax from subtotal...')
### WRITE SOLUTION HERE
raise NotImplementedError()
def summarize_order(order):
""" Summarizes the order
[IMPLEMENT ME]
1. Calculate the total (subtotal + tax) and store it in a variable named total (rounded to two decimals)
2. Store only the names of all the items in the order in a list called names
3. Return names and total.
Args:
order: list of dicts that contain an item name and price
Returns:
tuple of names and total. The return statement should look like
return names, total
"""
print_order(order)
### WRITE SOLUTION HERE
raise NotImplementedError()
This function is provided for you, and will print out the items in an order
def print_order(order):
print('You have ordered ' + str(len(order)) + ' items')
items = []
items = [item["name"] for item in order]
print(items)
return order
This function is provided for you, and will display the menu
def display_menu():
print("------- Menu -------")
for selection in menu:
print(f"{selection}. {menu[selection]['name'] : <9} | {menu[selection]['price'] : >5}")
print()
This function is provided for you, and will create an order by prompting the user to select menu items
def take_order():
display_menu()
order = []
count = 1
for i in range(3):
item = input('Select menu item number ' + str(count) + ' (from 1 to 5): ')
count += 1
order.append(menu[int(item)])
return order
'''
Here are some sample function calls to help you test your implementations.
Feel free to change, uncomment, and add these as you wish.
'''
def main():
order = take_order()
print_order(order)
# subtotal = calculate_subtotal(order)
# print("Subtotal for the order is: " + str(subtotal))
# tax = calculate_tax(subtotal)
# print("Tax for the order is: " + str(tax))
# items, subtotal = summarize_order(order)
if name == "main":
main()
#2.)
def read_file(file_name):
""" Reads in a file.
[IMPLEMENT ME]
1. Open and read the given file into a variable using the File read()
function
2. Print the contents of the file
3. Return the contents of the file
Args:
file_name: the name of the file to be read
Returns:
string: contents of the given file.
"""
### WRITE SOLUTION HERE
with open('sampletext.txt','r') as file:
print(file.readlines())
raise NotImplementedError()
def read_file_into_list(file_name):
""" Reads in a file and stores each line as an element in a list
[IMPLEMENT ME]
1. Open the given file
2. Read the file line by line and append each line to a list
3. Return the list
Args:
file_name: the name of the file to be read
Returns:
list: a list where each element is a line in the file.
"""
### WRITE SOLUTION HERE
with open('sampletext.txt','r') as file:
lines = []
for line in file_in:
lines.append(line)
raise NotImplementedError()
def write_first_line_to_file(file_contents, output_filename):
""" Writes the first line of a string to a file.
[IMPLEMENT ME]
1. Get the first line of file_contents
2. Use the File write() function to write the first line into a file
with the name from output_filename
We determine the first line to be everything in a string before the
first newline ('\n') character.
Args:
file_contents: string to be split and written into output file
output_filename: the name of the file to be written to
"""
### WRITE SOLUTION HERE
with open(file_contents,'w') as file:
file.write()
raise NotImplementedError()
def read_even_numbered_lines(file_name):
""" Reads in the even numbered lines of a file
[IMPLEMENT ME]
1. Open and read the given file into a variable
2. Read the file line-by-line and add the even-numbered lines to a list
3. Return the list
Args:
file_name: the name of the file to be read
Returns:
list: a list of the even-numbered lines of the file
"""
### WRITE SOLUTION HERE
raise NotImplementedError()
def read_file_in_reverse(file_name):
""" Reads a file and returns a list of the lines in reverse order
[IMPLEMENT ME]
1. Open and read the given file into a variable
2. Read the file line-by-line and store the lines in a list in reverse order
3. Print the list
4. Return the list
Args:
file_name: the name of the file to be read
Returns:
list: list of the lines of the file in reverse order.
"""
### WRITE SOLUTION HERE
raise NotImplementedError()
'''
Here are some sample commands to help you run/test your implementations.
Feel free to uncomment/modify/add to them as you wish.
'''
def main():
file_contents = read_file("sampletext.txt")
# print(read_file_into_list("sampletext.txt"))
# write_first_line_to_file(file_contents, "online.txt")
# print(read_even_numbered_lines("sampletext.txt"))
# print(read_file_in_reverse("sampletext.txt"))
if name == "main":
main()
Hi, could you explain line 6 code ? thank you!