Answer to Question #288215 in Python for h2zee

Question #288215

You get a list of products (products.txt) from a toy store. We want all products in the “party games” category of which there are still more than 10 in stock a price reduction giving € 1. You then create the file products_adapted.txt in which all data of the original file are saved.

In the products.txt file, you will find the following information:

Item name – Item type – Item price – Item VAT rate – Item stock In the modified file,

all prices of the articles concerned must be reduced by €1.

Block box;baby items;14.99;21%;15

Werewolves of Wakkerdam;board games;11.99;21%;25

Reading booklet: Good night;books;9.99;6%;12

Football;sports articles;9.99;21%;11

Doll: Emma; dolls; 19.99;21%;0

Uno;party games;9.99;21%;78

Indian suit;carnival items;14.99;21%;1

Spinner; hype articles;9.99;21%;127

Farm with animals;simulation toys;24.99;21%;3

Coconuts;board games;29.99;21%;5

Golf ball;sports articles;2.99;21%;16

Doll: Louis;dolls;19.99;21%;3

Goggles;sports articles;8.99;21%;6



1
Expert's answer
2022-01-17T16:12:20-0500
with open(filename) as file:
    lines = file.readlines()
    lines = [line.rstrip() for line in lines]


with open('filename') as f:
    lines = f.readlines()
with open("file.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)
f = open('file.txt') # Open file on read mode
lines = f.read().splitlines() # List with stripped line-breaks
f.close() # Close file
def process(line):
    if 'save the world' in line.lower():
         superman.save_the_world()
x = []
with open("myfile.txt") as file:
    for l in file:
        x.append(l.strip())
def print_output(lines_in_textfile):
    print("lines_in_textfile =", lines_in_textfile)

y = [x.rstrip() for x in open("001.txt")]
print_output(y)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = file.read().splitlines()
    print_output(file)

with open('001.txt', 'r', encoding='utf-8') as file:
    file = [x.rstrip("\n") for x in file]
    print_output(file)
f = open(filename)
# nothing in between!
try:
    # do stuff with f
finally:
    f.close()
with open(filename) as f:
    for line in f:
        if line.endswith('\n'):
            line = line[:-1]
        print(line)
infile = open('my_file.txt', 'r')  # Open the file for reading.

data = infile.read()  # Read the contents of the file.

infile.close()  # Close the file since we're done using it.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Define data
lines = ['     A first string  ',
         'A Unicode sample: €',
         'German: äöüß']

# Write text file
with open('file.txt', 'w') as fp:
    fp.write('\n'.join(lines))

# Read text file
with open('file.txt', 'r') as fp:
    read_lines = fp.readlines()
    read_lines = [line.rstrip('\n') for line in read_lines]

print(lines == read_lines)
from pathlib import Path
file_path = Path("C:/path/file.txt") 
lines = file_path.read_text().split_lines()
# ... or ... 
lines = [l.rstrip() for l in file_path.open()]


import os

# handle files using a callback method, prevents repetition
def _FileIO__file_handler(file_path, mode, callback = lambda f: None):
  f = open(file_path, mode)
  try:
    return callback(f)
  except Exception as e:
    raise IOError("Failed to %s file" % ["write to", "read from"][mode.lower() in "r rb r+".split(" ")])
  finally:
    f.close()


class FileIO:
  # return the contents of a file
  def read(file_path, mode = "r"):
    return __file_handler(file_path, mode, lambda rf: rf.read())

  # get the lines of a file
  def lines(file_path, mode = "r", filter_fn = lambda line: len(line) > 0):
    return [line for line in FileIO.read(file_path, mode).strip().split("\n") if filter_fn(line)]

  # create or update a file (NOTE: can also be used to replace a file's original content)
  def write(file_path, new_content, mode = "w"):
    return __file_handler(file_path, mode, lambda wf: wf.write(new_content))

  # delete a file (if it exists)
  def delete(file_path):
    return os.remove() if os.path.isfile(file_path) else None

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS