473,608 Members | 2,074 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to read data into an array

ryno du preez
91 New Member
HI all
I'm reading data from a CSV (text file) with a "| " as the denominator. Every is working as planned but I'm having a problem with the last 3 lines of code. In the text Document the 'RB' (Body) has more than one entry exp.
RB | INV000111 | price to be charged
RB | INV000112 | price 2 to be charged

some has more then TWO entry. Now the problem being

When Python reads the CSV it only writes the Second line to the PDF INV000112 not both lines as it is displayed.

How can I get it to write Both lines as displayed in the text file


Expand|Select|Wrap|Line Numbers
  1. db = csv.reader(open('C:/Users/rynod/Desktop/cpc.txt','rb'), delimiter = '|', quotechar='"')
  2.     for row in db:
  3.         for field in enumerate(row):
  4.             if 'H' in field:
  5.                #Customer Details
  6.                CustPAName = row[9]
  7.                CustPA1 = row[10]
  8.                CustPA2 = row[11]
  9.                CustPA3 = row[12]
  10.                CustPA4 = row[13]
  11.                CustPA5 = row[14]
  12.                CustFAName = row[18]
  13.                CustFA1 = row[19]
  14.                CustFA2 = row[20]
  15.                CustFA3 = row[21]
  16.                CustFA4 = row[22]
  17.                CustEMail = row[15]
  18.                #Sharp Details
  19.                SharpAddress1 = row[2]
  20.                SharpAddress2 = row[3]
  21.                SharpAddress3 = row[4]
  22.                SharpAddress4 = row[5]
  23.                SharpTel = row[6]
  24.                SharpFax = row[7]
  25.                Model = row[16]
  26.                Serial = row[17]
  27.                Account = row[25]
  28.                OurRef = row[27]
  29.             elif 'RB' in field:
  30.                print(row)
  31.                Decs = row 
Mar 25 '14 #1
3 2181
bvdet
2,851 Recognized Expert Moderator Specialist
Why do you need to do a nested for loop? You should be able to do it in one loop. Why not compile a dictionary instead of assigning so many variables? It would work something like the following where data is a line in db
Expand|Select|Wrap|Line Numbers
  1. fields = ['SharpAddress1',
  2.           'SharpAddress2',
  3.           'SharpAddress3',
  4.           'SharpAddress4',
  5.           'SharpTel',
  6.           'SharpFax']
  7.  
  8. data = [0,1,2,3,4,5,6,7,8,9,10]
  9.  
  10. dd = dict(zip(fields, data))
I am not sure why only one "RB" line is printed other than it has something to do with the nested loop or your use of enumerate. Could you post a representative portion of the CSV file?
Mar 25 '14 #2
ryno du preez
91 New Member
I'm trying to write a report in python where the data is read from a text file with CSV and then using report lab producing a PDF file(Invoice)

In the text file We have different sections 'H' Header 'B' Body ect. so that is why I'm using more then one loop. it is reading the text file and using row to assign it to a verable that gets coped to the PDF.
I manage to get it to read the RB section by using the following
Expand|Select|Wrap|Line Numbers
  1.     data = []
  2.             for i in range(1):   
  3.                 if 'RB' in field:
  4.                    data.append(row[3])
  5.                    print(data[1:2])
  6.                 cal = str(data[0:1])
  7.                 cal2 = str(data[1:2])
But the problem is now it shows it as a list as a string with the '[]' how do I get the '[]' not to show.

['546 @ 0.0879 cents = R47.99']
['165 @ 0.0967 cents = R15.96']

And also I don't thing this is very efficient because it will break if I have more then 2 entry

And as you probably guest I'm also just started learning python.
Thanks for your help so far
Mar 25 '14 #3
dwblas
626 Recognized Expert Contributor
Your first problem is using enumerate
Expand|Select|Wrap|Line Numbers
  1. row = ["ZHZ", "AH", "HA"]
  2. for field in enumerate(row):
  3.     print field, "--> H",
  4.     if 'H' in field:
  5.         print "foumd"             
  6.     else:
  7.         print "     NOT found" [
You don't use it so if we take it out
Expand|Select|Wrap|Line Numbers
  1. row = ["ZHZ", "AH", "HA"]
  2. for field in row:
  3.     print field, "--> H",
  4.     if 'H' in field:
  5.         print "foumd"             
  6.     else:
  7.         print "     NOT found" 
but this will find any "H" anywhere in the record. Is that what you want to do? Some test data would help.

use .join() to convert a list to a string
Expand|Select|Wrap|Line Numbers
  1. print("*".join(data[1:2]))
but data[1:2] == data[1] so you can just print data[1] in this specific case.

Every is working as planned but I'm having a problem with the last 3 lines of code. In the text Document the 'RB' (Body) has more than one entry exp.
RB | INV000111 | price to be charged
RB | INV000112 | price 2 to be charged
Using csv is overkill IMHO in this case. Just read the file and split each record.
Expand|Select|Wrap|Line Numbers
  1. """
  2. row = ["ZHZ", "AH", "HA"]
  3. """ commented out because "test_it" is used to simulate the file
  4. with open(file_name, "r") as fp:  ## replaced by test_it
  5.     for rec in fp:                ## replaced by for rec in test_it
  6. """
  7. test_it= ['ABC | INV001 | price',
  8.           'HB | INV000111 | price to be charged',
  9.           'RB | INV000112 | price 2 to be charged']
  10.  
  11. for rec in test_it:
  12.     data = rec.split("|")
  13.     print data[0], "--> HB",
  14.     if 'HB' == data[0].strip(): ## strip white space in file
  15.         print "foumd"             
  16.     else:
  17.         print "     NOT found" 
And also I don't thing this is very efficient because it will break if I have more then 2 entry
Write each entry to the pdf file as it is found, then it doesn't matter how many there are.
Mar 25 '14 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
4422
by: Mike Dole | last post by:
I'm working on a client - server application based on the 'How to Sockets Server and How to Sockets Client' code from the Visual Basic ..NET Resource Kit. Since I want to be able to send 'big strings' instead of 'one liners' I check the streams for terminators. I'm having problems with the connection, I've been looking and debugging for 2 weeks now (debugging with an emulator is terribly slow..) but I'm not getting it...
3
5502
by: Mark Dunmill | last post by:
I can't create a Constant/Read-only array field in managed C++ classes - doesn't allow the keyword const pointer to const object on array fields in managed C++ classes. e.g. Want to define a read/only field for an empty array (so all the empty arrays of the given type can use the same object) however because the pointer in the field cannot be marked as constant then it is possible that any external party can alter this pointer to reference...
12
6593
by: Ron | last post by:
What is the VB equivalent of the READ...DATA statements in QuickBasic? Thanks
7
16119
by: rossum | last post by:
Is there any way of creating a read only reference to an array? My class includes a private array of bytes with a Property to access it. However, I do not want users to use the returned reference to modify the array; modifications are only allowed through the property, which includes error checking. I have been trying to use Array.AsReadOnly() to return a read only reference, but with very little success: public class Foo { private...
1
2832
by: Cristina | last post by:
Hello , How can I read an array of integers from an external file ? Each array is in one line and i don-t know the number of integers.I don`t want to use a string of chars, I need them as integers to be able to sort them further. Please help me if you could Thanks
4
11044
by: Francois Stander | last post by:
Hi, hope someone can help me. It seems imposible to read data from a server, however, I can read the validation data from the server and hold it in dataviews . datasets or data tables in my asp "load" page. I would like to use these data (which I presume is in some form of html or xml) in my HTML portion of the asp page. The data must be read using java script and after lots of calculations perform on it - be written to xml controls. I can...
2
10686
by: Bill Fallon | last post by:
I have a VS2005 VB.Net windows form application deployed to a share drive. The windows explorer security permissions for this application (.exe) file is set for Everyone with List Folder/Read Data not allowed. This is done so that users cannot take away a copy of the .exe file. When I execute the ..exe from the client computer I get .Net Framework Initialization Error, Unable to find a version of the runtime to run this application. The...
5
43417
by: barbara_dave | last post by:
Hi All, I need to read data from a Excel spreadsheet, but I got the problem when I tried the code below: StringBuilder sbConn = new StringBuilder(); sbConn.Append(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" ); sbConn.Append(excelFile); sbConn.Append(";Extended Properties="); sbConn.Append(Convert.ToChar(34));
0
3962
by: mwenz | last post by:
I am trying to update an Access table using OLEDB in VB.Net 2005. I can add rows but I cannot update them. Code to instantiate the Access database and table... Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & db.Name) conn.Open() Dim oda As New OleDb.OleDbDataAdapter("select " & sqlCols & " from ;", conn) Dim cb As New OleDb.OleDbCommandBuilder(oda) cb.QuotePrefix = "" oda.UpdateCommand =...
0
8087
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8025
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8493
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6847
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6023
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3993
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4053
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1363
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.