473,404 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Req: ? Python command to append data to file

17
Hi

This is my first attempt at writing Python script - it's probably a bit ambitious, but there again, whatever doesn't kill you makes you stronger... ;-)

I'm trying to write a script for a datalogger, which will import data from a laboratory flow meter at regular user-defined intervals via a serial port connection, then save it as a CSV file which can then be opened in Excel for analysis.

The imported data is in the form of an 18-byte long comma delimited ASCII character string which I've helpfully called "data".
e.g.: 12.345,100.23,22.5

Each comma delimited value will represent a column, and each string of data will represent a seperate row in the Excel spreadsheet.

So far (with some help from the Bytes community!) I've managed to import a string of data, print it to screen, and save it as a csv file using the code listed below. My "Print to screen" and "Save to file" routines are embedded in a "While" loop, which loops round repeatedly until the required (user defined) number of data strings have been collected.

I can see all the results printed to the screen, but using my "Save to file" routine in this way means that the data file is constantly being over-written, and the only data that ends up saved to the file is the last string to be collected.

I was wondering if there is a Python command along the lines of "append to file", that I could use which would allow me to write successive strings of data to the .csv file without over-writing the previous entries.

I guess the alternative is to use Python to keep adding each new data string to the end of the previous ones,
seperated by a suitable "new row" character, to make one long "master string" for subsequent import into Excel. However, the "master string" may end up rather long - I'm planning to collect data at a rate of 1 new 18 byte string every 10 seconds for a couple of hours! Also, if the data connection or power supply was interrupted at any stage during data acquisition, all the data collected might be lost if this method was used...

I'm sure this must be a fairly routine problem, but I'm not sure of the best solution, and would be very grateful for your help & advice.

Many thanks in anticipation

Dave


Expand|Select|Wrap|Line Numbers
  1. #Write recieved data to file
  2.     data=data + "\n"
  3.     print "Writing data to file 'c:/test/a.csv'"
  4.     fob=open('c:/test/a.csv','w')
  5.     fob.write(data)
  6.     fob.close()
  7.  
Sep 15 '10 #1
6 6760
bvdet
2,851 Expert Mod 2GB
Minor adjustment. Open the file in "append" mode.
Expand|Select|Wrap|Line Numbers
  1. f = open("file_name", 'a')
Sep 15 '10 #2
Dave067
17
Many thanks for the rapid reply.

I got the whole thing working last night using the quick & dirty "master string" technique described above, and it seems to work fine - I can now send and receive data from the flow meter at user-defined intervals, and save the result as a .csv which opens in Excel :-)

A few quickie related questions:

1) How long can a single string can be before it causes problems? Is it better practice to use the append file method instead?

2) When I am reading & writing to file or to COM1 port, do I need to enclose every single read or write command within open and close file/port commands; or can I get away with doing this less frequently...e.g. just at the start and end of the main code?

3) Do I need to execute a flush command periodically when writing to file or COM ports?

4) How do I get Python to create a brand new file in a Windows directory using a string variable as the file name?

Sorry for the dumb questions - if there is a good tutorial on line/in print that you could recommend which covers these issues at a basic level, I'd be very grateful.

Thanks again for your help

Dave
Sep 16 '10 #3
bvdet
2,851 Expert Mod 2GB
1. The length of the string is only limited by available memory. String concatenation (string addition) is expensive. I would accumulate the strings in a list and write the data to a file once. Example:
Expand|Select|Wrap|Line Numbers
  1. output = []
  2. output.append("string1")
  3. output.append("string2")
  4. fileObj.write("\n".join(output))
2. If you accumulate the strings in a list, I would open and close the file each time. When a file is closed, the output buffers are flushed, assuring the data is written.

3. No. See #2.

4.
Expand|Select|Wrap|Line Numbers
  1. var = "file_name"
  2. path = "C:\\dirname\\"
  3. fileObj = open("%s%s.dat" % (path, var, 'w'))
If portability is an issue, it's better to use os.path.join() to concatenate the path and file name.
Sep 16 '10 #4
bvdet
2,851 Expert Mod 2GB
I reread your earlier post where you were concerned about losing your data connection. You could design your code to immediately write the data to disk instead of failing by using a try/except block. If you are concerned about power interruption, write the data to disk each time it is collected. I doubt if opening a file, writing a small amount of data, and closing the file every 10 seconds would be noticeable.
Sep 16 '10 #5
Dave067
17
Thanks again bvdet!
Really appreciate you taking the time to help out with my queries.

Have a great weekend!
Best wishes

Dave
Sep 17 '10 #6
bvdet
2,851 Expert Mod 2GB
My pleasure. I'm glad to help.

BV
Sep 18 '10 #7

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

Similar topics

2
by: leroybt.rm | last post by:
I don't understand why this does not work: <FILE1> test1.py #Import Packages import string # data=0 data=data+1
2
by: SunX | last post by:
Question from a newbie. How do you write out a data file of floating point numbers? file.write only takes strings. Many thanks.
3
by: Jonathan Buckland | last post by:
Can someone give me an example how to append data without having to load the complete XML file. Is this possible? Jonathan
14
by: vbMark | last post by:
Greetings, This seems like it should be simple but I can't figure out how to do this. I just want to append binary file 2 on to the end of binary file 1. Sample code please? Thanks!
6
by: Reggie | last post by:
Hi and TIA. I have an OleDB connection to an Access db which I connect to and place data from a table into a recordset. What I want to do is copy this recordset to an SQL table. I have no...
1
by: Andrew McCall | last post by:
Hi Folks, I am building an application under multiple OS's, and I wanted to give my application For example, the test application I am working on is a calculator and I would like to have a...
17
by: News | last post by:
Hi everyone, My goal is to pull command switches/options from a file and then assign the values to select variables which would eventually be included in a class object. The data file looks...
0
by: h112211 | last post by:
Hi all, I'm using the Windows version of Python 2.4.3 and everything worked okay until I installed PyGreSQL. Well, in fact the installation went fine, but when I try to run my script from IDLE I...
1
by: TP | last post by:
Hi everybody, I try to find a quick way to redirect the standard output of a Python command (for example: print "message") to a python variable "foobar". Ok, in this simple example, I could do...
3
by: premMS143 | last post by:
How to append Data to an existing Excel file? means, I'm using VB as front end & once I exported the data to Excel file & saved it as 'ABC.xls'. Now, the question/doubt is; I addded some more...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...
0
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,...

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.