473,799 Members | 2,936 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Noobie Question reg Delimited Text

3 New Member
Hope the Community can bear with me as I muddle with the vocabulary since I am not really sure if I am going about this the correct way.

My question is as follows:

If I had some sample data in the form of delimited text, in this case comma-delimited (eg. canned_data.txt ) and the format looked roughly like this:

name,age,occupa tion,status
"joe blow",21,salesm an,married
"hanna montana,19,ente rtainer,single

etc...


I am confused with how to go about

1) importing this file into Python for reading line-by-line for eventual parsing,splitti ng, general manipulation to a new output file
2) the exact terminology/vocab (I have come across array,matrix,ta ble, etc.)


So far I would do something like this:
Expand|Select|Wrap|Line Numbers
  1. # start of my module
  2. tInputName = raw_input("Enter the name of your delimited input file:") #canned_data.txt in the same directory as module
  3. tOutputName= raw_input("Enter the name of your output file:")
  4. getData = open(tInputName,r)
  5. getData = input.readlines()
  6. for line in getData
  7.    getData = line.split(",") #my series of general data manipulation
  8.    getData = line.upper #another eg of manipulation
  9. output.writelines(tOutputName)
  10. output.close()
  11. if output.close == true
  12. print "The file:", tOutputName, " was created"
  13. raw_input()
  14. else
  15. output.close ==false
  16. print "Failed creating  ", tOutputName
  17. raw_input()

In a nutshell, could someone help me vett the above?
Sincerely,
Nick
Dec 12 '08 #1
1 1983
bvdet
2,851 Recognized Expert Moderator Specialist
Please use code tags when posting code!!

Python for loops and if statements require a colon for proper syntax.
Example:
Expand|Select|Wrap|Line Numbers
  1. for name in nameList:
  2.     print name
  3.  
  4. if name == "Fred":
  5.     print "Fred's here."
  6. else:
  7.     print "I don't know this guy."
Generally, if an error occurs when opening, reading, or writing to a file, an IOError exception is raised. This error can be caught with a try/except block.
Example:
Expand|Select|Wrap|Line Numbers
  1. >>> try:
  2. ...     f = open('abc')
  3. ... except IOError, e:
  4. ...     print e
  5. ...     print e.errno, e.strerror, e.filename
  6. ...     
  7. [Errno 2] No such file or directory: 'abc'
  8. 2 No such file or directory abc
  9. >>> 
File I/O seldom errors except when invalid file names or paths are attempted.

Following are examples of opening a file, manipulating the data, and writing to another file. The first example uses list comprehensions. The second is the equivalent without the list comprehensions.
Expand|Select|Wrap|Line Numbers
  1. infile = open('names.txt')
  2. outfile = open('names_reversed.txt', 'w')
  3.  
  4. results = []
  5. for line in infile:
  6.     results.append([item for item in line.strip().split(',')[::-1]])
  7. infile.close()
  8.  
  9. outfile.write('\n'.join([','.join(item) for item in results]))
  10. outfile.close()
  11.  
  12. ''' output file contents
  13. status,occupation,age,name
  14. married,salesman,21,joe blow
  15. single,entertainer,19,hanna montana
  16. '''
  17.  
  18. infile = open('names.txt')
  19. outfile = open('names_reversed1.txt', 'w')
  20.  
  21. results = []
  22. for line in infile:
  23.     lineList = line.strip().split(',')
  24.     lineList = lineList[::-1]
  25.     results.append(lineList)
  26. infile.close()
  27.  
  28. output = []
  29. for item in results:
  30.     output.append(','.join(item))
  31.  
  32. outfile.write('\n'.join(output))
  33. outfile.close()
Dec 12 '08 #2

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

Similar topics

4
4873
by: Christine Forber | last post by:
I wonder if anyone knows of some javascript code to check a comma-delimited list of email addresses for basic formating. What I'm looking for is the javascript code to check a form field on form submission. If there is an entry in the field, does it match the following: text@text.text, text@text.text,text@text.text where each address is between commas and each address is in the format
3
7036
by: Ben | last post by:
Hi all - I am having a bit of trouble and thought maybe someone in this group could shed some light. Here's the skinny... I am creating an automated process to import a bunch of text files into Access. I want to avoid creating a separate "Spec" for each file (there are over 180 files) and instead want to code my own dynamic importing rules. So far it's been going fine, except for one item...
1
11194
by: The Bear | last post by:
I have populated a dataset with a tab delimited text file. When the changes are made in the dataset, I then want to write those changes from the dataset to a tab delimited text file. How do I write each record to that text file. If anyone one knows I would really appreciate the help TB
3
2440
by: Joe Fisherman | last post by:
I have used regex to parse a huge text file, and grab a tab delimited portion of it. I often use comma delimited text files, and use Jet Oledb4. I read that I would need an ini if the file wasn't comma delimited - if this is true, I am not sure of the easiest process to create an ini. The string has a header. My string looks like: "Call" "Date" "Time" "Call Period" "From" "Call Type" "Number Called" "To" "Call Length" "Local Airtime...
2
4775
by: denisel | last post by:
Hi, We will be conducting surveys through SurveyMonkey online and will be importing the answers by tab delimited or comma delimited file into access. I was wondering if there is specific way to import delimited files into Access or Is there a specific way I should design the survey online so Access can recognize the file? Here is my table structure to give you an idea on where I'm coming from. Thank you so much in advance!!! ...
1
8188
by: Fordraiders | last post by:
vb.net 2003 Office 2003 What I have: C:\TestData\Input.txt Text File Pipe Delimited : 4 columns Of data example: 00001|NO BRAND NAME ASSIGNED|6DU27|M3-.5 X 6 FLAT HD SOCKET CAP SCREW, CL10.9, ALLOY STEEL 00002|NO BRAND NAME ASSIGNED|6DU28|M3-.5 X 8 FLAT HD SOCKET CAP SCREW,
4
1229
by: Ron | last post by:
How do I display delimited text on multiple lines in a listbox? For example in my textbox I have this: Joe Doe,123 Street,Mytown and In a listbox then I want to display: Joe Doe 123 Street Mytown
2
2135
by: Ron | last post by:
so if my textbox is named textbox1 and my listbox is named ltsdisplay, for the button that would make this all happen I would just need to: lstdisplay.items.textbox1(delimited.Split(",".ToCharArray())) is that right? or no? I try this and I get an error...
6
22566
by: =?Utf-8?B?UmljaA==?= | last post by:
'--this code works but only reads text into one column when contains multiple cols Dim ds1x As New DataSet Dim ConStr As String = _ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\dir1A\;Extended Properties=""Text;HDR=No;FMT=Delimited\""" Dim conn1x As New OleDb.OleDbConnection(ConStr) Dim dax1 As New OleDbDataAdapter("Select * from testabc1x.txt", conn1x)
0
9686
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
9540
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
10475
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10250
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...
0
10026
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9068
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...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
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...
3
2938
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.