# Can someone kindly advise how to code the below

**URL:** <https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640>\
**Category:** Python Help\
**Created:** [January 7, 2024, 7:01am UTC](https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640 "2024-01-07T07:01:06Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![nicemanyx](https://avatars.discourse-cdn.com/v4/letter/n/c2a13f/32.png) [@nicemanyx](https://discuss.python.org/u/nicemanyx)\
**Post date:** [January 7, 2024, 7:01am UTC](https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640/1 "2024-01-07T07:01:06Z")

</div>

i need to read a csv input file, then to calculate the transaction values and only output the summary to a text file:

input file - itemactivities.csv: Item, sales qty, value  
transaction value = sales qty \* value  
output only one record per item to a text file: item no, total transaction values, total sales.

i have the first part of the codes done by the instructor as below, but not sure how to read from the input file and how to output to the text file, also not too sure about the file handling.  
Do I read from the itemactivities file or read from the itemactivities list that has created by the instructor

# create a file path to csv file.

fp = Path.cwd()/“itemactivities.csv”

# read the csv file.

with fp.open(mode=“r”, encoding=“UTF-8”, newline=“”) as file:  
reader = csv.reader(file)  
next(reader) # skip header

```
itemactivities=[] 

for row in reader:
      itemactivities.append([row[0],row[1],row[2]])   

```

#start your calculation of value here  
#print the summary info to a text file

---

<div class="post-metadata">

**Author:** ![barry-scott](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@barry-scott](https://discuss.python.org/u/barry-scott)\
**Post date:** [January 7, 2024, 9:15am UTC](https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640/2 "2024-01-07T09:15:15Z")

</div>

> [@nicemanyx](#):
>
> read from the itemactivities list

Read from the list that was made from the file contents.

Use the `print` function to output text.

Please use the preformatted text to include source code.  
It is the `</>` button and show text like this:

```auto
print(“hello”)

```

---

<div class="post-metadata">

**Author:** ![nicemanyx](https://avatars.discourse-cdn.com/v4/letter/n/c2a13f/32.png) [@nicemanyx](https://discuss.python.org/u/nicemanyx)\
**Post date:** [January 7, 2024, 9:40am UTC](https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640/3 "2024-01-07T09:40:09Z")

</div>

Thanks Barry very much for your reply,

i think i have to do : for data in intemactivities:  
can i know how do i refer/obtain the field names such like item, sales qty etc.

Also, can i know if the list contains multiple rows just like the input csv file?

filepath = Path.cwd()/“summaryfile.txt”  
Print(filepath) - kindly advise if this is the right code to use for the printing to the output file and path.

appreciate your kindly advice.

---

<div class="post-metadata">

**Author:** ![MariaBu](https://avatars.discourse-cdn.com/v4/letter/m/ea5d25/32.png) [@MariaBu](https://discuss.python.org/u/MariaBu)\
**Post date:** [January 7, 2024, 9:53am UTC](https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640/4 "2024-01-07T09:53:42Z")

</div>

#Think of this like a PSEUDO code to give you advise on ideas behind

# I focus on the part going from csv file to calculation to a text file

import sys

try:  
csvfile = open(“YOURCSVFile.csv”)  
except:  
print(“Could not open YOURCSVFile.csv”)  
sys.exit(0)

try:  
textfile = open(“YOURTEXTFILE.txt”, w)  
except:  
print(“Could not open YOURTEXTFILE.txt”)  
sys.exit(0)

#Read one line of data  
z = data.readline()

#For each line in z  
while z:  
#split the data into pieces by the separator ; in use within the csv file  
li = z.split(“;”)  
#substitute a , by a . where csv is showing a comma for example in 1234,45 where Python requires a .  
#On that you need to know, where you have a float numbers within each line and do so accordingly  
#You would use the fields along their order like li[0], li [1] etc.  
# With N being the number of your field. Test print to see if you get the requried result  
print(int(li[N1] float(li[N2].replace(“,”, “.”)))  
# For the calculation you need the values as integer or float.  
var1=int[li[N1])  
var2=float(li[N2].replace(“,”, “.”))  
# Do the calculation now  
YOUR\_CALCULATION  
# For the writing you need them all as string.  
var3=str(var1)  
var4=str(var2)  
textfile.write =(var3, var4)

csvfile.close()  
textfile.close()

---

<div class="post-metadata">

**Author:** ![cameron](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/cameron/32/2658_2.png) [@cameron](https://discuss.python.org/u/cameron)\
**Post date:** [January 7, 2024, 9:55am UTC](https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640/5 "2024-01-07T09:55:38Z")

</div>

> i need to read a csv input file, then to calculate the transaction  
> values and only output the summary to a text file:
> 
> input file - itemactivities.csv: Item, sales qty, value  
> transaction value = sales qty \* value  
> output only one record per item to a text file: item no, total transaction values, total sales.

That seems clear. Is it clear to you? I mean: you understand what you  
want as the result?

> i have the first part of the codes done by the instructor as below, but not sure how to ready from the input file and how to output to the text file, also not too sure about the file handling.

Let’s look at what you’ve go so far below…

> Do I read from the itemactivities file or read from the itemactivities list that has created by the instructor

I would process the list, because the instructor has read the file for  
you in order to make the list.

Let’s walk through the existing code:

```
 # create a file path to csv file.
 fp = Path.cwd()/"itemactivities.csv"

```

This makes a “Path” object representing the full path to the  
`"itemactivities.csv"` file. Kind of elaborate really if you don’t care  
about the full path - the unadorned filename `"itemactivities.csv"` is  
enough.

```
 # read the csv file.
 with fp.open(mode="r", encoding="UTF-8", newline="") as file:

```

There’s a few things going on here. `fp.open` calls the `Path` object’s  
`open` method to open the file, in read mode (`'r'`), assuming a text  
encoding of `UTF-8` (most modern files use this) in “universal newlines”  
mode. The result of that is an open file object. The gnarly details of  
this, should you care, are here:

> **[Built-in Functions](https://docs.python.org/3/library/functions.html#open)**
>
> The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...

(because `Path.open` just calls the buoltin `open` function).

The `with .... as file:` takes that open file object and binds it to the  
variable named `file`. And then iit uses that object as a “context  
manager”; the important effect here is that when you leave the body of  
the `with` statement the file object is automatically closed for you, so  
you won’t see a call to `file.close()` later - that’s done for you.

```
     reader = csv.reader(file)

```

This passes the `file` variable (your open file) to the `reader`  
function from the `csv` module, which understands the format of a CSV  
file and returns an iterator whose values are rows from the file. We  
bind that iterator to the variable `reader`. An iterator is a thing you  
can iterate over - we use them a lot to provide a sequence of values,  
and for-loops know how to use the directly.

```
 next(reader) # skip header

```

For your purposes, you don’t care about the header line in the CSV file.  
Calling `next()` on an iterator obtains the next value from it and  
returns it. We don’t assign that value to anything, so the value is  
discarded, which effectively skips the header line as the comment says.

```
 itemactivities=[]

```

Here we make an empty list (`[]`) and bind it to the variable  
`itemactivities`.

```
 for row in reader:

```

As mentioned, for-loops know how to use iterators directly. This takes  
values from the iterator `reader` and assigns each to the variable  
`row`, which you then use inside the loop.

```
       itemactivities.append([row[0],row[1],row[2]])

```

This is the body of the loop. It takes the first 3 values from the row  
(`row[0]`, `row[1]`, and `row[2]`) and makes a 3-element list containing  
them: [row[0],row[1],row[2]]  
According to what you said at the beginning, those 3 values should be  
Item, sales qty, value.  
Then we append that new list to `itemactivities`.

After the loop, the list `itemactivities` conatins an entry for each  
data row from the CSV file.

So you’ve got this list, and no longer need to read the CSV file.

Now the fun begins, which you need to write yourself. We generally don’t  
write the code for you, but will make suggestions and answer questions  
you have.

1: #start your calculation of value here

Can you describe how you’d do this? As a person with a piece of paper.  
Since you need a total of sale items and sale values per item you likely  
want a `dict`, which is a mapping of a key value (such as the item) to a  
value (which could be a 2-element list containing the tiotals for that  
item).

Can you describe what you’d do with these?

2: #print the summary info to a text file

To write stuff to a file you need to:

- open a text file for write
- print the things you want to the file

Given that you’ve got code to open a file for read above, how would you  
open a file for write?

If you’ve got a `dict` (let’s pretend you named it `totals`), how would  
you print a line into the file for each entry in `totals`? See the docs  
for the built in `print()` function as well:

> **[Built-in Functions](https://docs.python.org/3/library/functions.html#print)**
>
> The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...

Let us know where you get to.

---

<div class="post-metadata">

**Author:** ![barry-scott](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@barry-scott](https://discuss.python.org/u/barry-scott)\
**Post date:** [January 7, 2024, 10:37am UTC](https://discuss.python.org/t/can-someone-kindly-advise-how-to-code-the-below/42640/6 "2024-01-07T10:37:38Z")

</div>

> [@nicemanyx](#):
>
> appreciate your kindly advice.

Are you working with a python tutorial to get you python skills?  
It will make things a lot easier for you if you do.  
There is this one [The Python Tutorial — Python 3.12.1 documentation](https://docs.python.org/3/tutorial/index.html) and there are others if you find this does not suit you.
