473,804 Members | 3,909 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Odd behavior writing file...

1 New Member
I'm guessing I'm missing something obvious here, but I have searched around and re-read my Python books and references on simple file writing and I can't see the answer. I am running this in Windows XP in IDLE.

I have some simple code I wrote to open a large log file with 39 extra characters starting each line that I want to strip out. Then I just want to rewrite the lines in a new file without those 39 preceding characters per line.

Expand|Select|Wrap|Line Numbers
  1. output = open('newlogfile', 'w')
  2. for line in open('ClientLog_072507_17302.log','r'):
  3.     clipline = line[39:]
  4.     output.write(clipline)
  5. output.close
  6. output = open('testlogfile', 'w')
  7.  
As you can see I am opening another output logfile at the end. When I ran the code without that last line it never seemed to write to the first output file. I could print the results correctly in the line just prior to the output.write line, but the output file size was always zero. As soon as I opened a new bogus file with the last line, it wrote the first file with all my data.

So, this code actually works for my purposes, but I'd like to know what I did wrong for it not to work without opening another bogus file. I added the output.close even though I thought it wasn't absolutely necessary for simple tasks like this. I also originally had the string handling code in the same line as the output.write but I broke it up into two lines to see if I was making some mistake with the string.

The logfile to read is in the same directory as the program so I didn't include a path.

Any help anyone can provide in pointing out what I might have gotten wrong in the output file handling would be greatly appreciated. Since I have the cludgy workaround, there is no urgency in this. But I'd like to know the right way to do this. Thanks
Aug 10 '07 #1
4 1803
bvdet
2,851 Recognized Expert Moderator Specialist
I'm guessing I'm missing something obvious here, but I have searched around and re-read my Python books and references on simple file writing and I can't see the answer. I am running this in Windows XP in IDLE.

I have some simple code I wrote to open a large log file with 39 extra characters starting each line that I want to strip out. Then I just want to rewrite the lines in a new file without those 39 preceding characters per line.

Expand|Select|Wrap|Line Numbers
  1. output = open('newlogfile', 'w')
  2. for line in open('ClientLog_072507_17302.log','r'):
  3.     clipline = line[39:]
  4.     output.write(clipline)
  5. output.close
  6. output = open('testlogfile', 'w')
  7.  
As you can see I am opening another output logfile at the end. When I ran the code without that last line it never seemed to write to the first output file. I could print the results correctly in the line just prior to the output.write line, but the output file size was always zero. As soon as I opened a new bogus file with the last line, it wrote the first file with all my data.

So, this code actually works for my purposes, but I'd like to know what I did wrong for it not to work without opening another bogus file. I added the output.close even though I thought it wasn't absolutely necessary for simple tasks like this. I also originally had the string handling code in the same line as the output.write but I broke it up into two lines to see if I was making some mistake with the string.

The logfile to read is in the same directory as the program so I didn't include a path.

Any help anyone can provide in pointing out what I might have gotten wrong in the output file handling would be greatly appreciated. Since I have the cludgy workaround, there is no urgency in this. But I'd like to know the right way to do this. Thanks
The file object must be closed properly to flush the data to disk:
Expand|Select|Wrap|Line Numbers
  1. output.close()
file.close() is a file method.
Aug 10 '07 #2
bvdet
2,851 Recognized Expert Moderator Specialist
If your log file is not huge, you can do something like this which should be more efficient:
Expand|Select|Wrap|Line Numbers
  1. outList = [line[39:] for line in open('ClientLog_072507_17302.log','r')]
  2. output = open('newlogfile', 'w')
  3. output.write(''.join(outList))
  4. output.close()
Aug 10 '07 #3
bartonc
6,596 Recognized Expert Expert
If your log file is not huge, you can do something like this which should be more efficient:
Expand|Select|Wrap|Line Numbers
  1. outList = [line[39:] for line in open('ClientLog_072507_17302.log','r')]
  2. output = open('newlogfile', 'w')
  3. output.write(''.join(outList))
  4. output.close()
FingerDemon: You left off the parentheses on line 5. It should read:
Expand|Select|Wrap|Line Numbers
  1. output.close()
BVDet: What's wrong with the writelines() method?
Expand|Select|Wrap|Line Numbers
  1. output.writelines(outList)
Aug 10 '07 #4
bvdet
2,851 Recognized Expert Moderator Specialist
FingerDemon: You left off the parentheses on line 5. It should read:
Expand|Select|Wrap|Line Numbers
  1. output.close()
BVDet: What's wrong with the writelines() method?
Expand|Select|Wrap|Line Numbers
  1. output.writelines(outList)
You are correct, writelines() would be better in this case. join() may be useful when a '\n' is required between lines.
Aug 10 '07 #5

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

Similar topics

7
3999
by: Aaron Bertrand - MVP | last post by:
Based on a complaint that one of my articles just links to the MS documentation, I'm writing a tutorial on FileSystemObject. However I'm currently getting stalled by this bug. Environment: Windows Server 2003, IIS 6.0, VBScript 5.6, all windows and IE update patches (to my knowledge). From msdn.microsoft.com/library/en-us/script56/html/jsmthcreatetextfile.asp
5
1895
by: Danny Anderson | last post by:
Hola- I didn't get any responses on a previous post, so I am trying to reword my problem and post compile-able code that exhibits the behavior I am describing. On the second iteration of the loop below, the file opened is the default (which in this case is ".csv", which makes a 'hidden' file for Linux folk). The step that prompts for a file name step is skipped completely. Why? Is this a cin issue or does it have something to do with...
3
1331
by: sstreaker | last post by:
I'm serving an MP3 file via a BinaryWrite from an ASPX file. If I have Content-Disposition set to "inline", WMP opens as expected but hits my ASPX page 3 times and then finally play the file. This is not desirable because the impact on the server is idential to that if 3 different clients hit the same page. If I have Content-Disposition set to "attachment", IE prompts with Save/Open as expected, and if I choose save, the ASPX page is...
4
6876
by: welch | last post by:
while taking some rough disk performance measures on windows machines, and snooping with FileMon, i've noticed some odd behavior here's the little nul-writer i'm running: def writeTest(nBlocks, blockSize): """write nBlocks*blockSize nuls to a file""" f = open("writeTest.out", "wb") nulBlock = '\0'*blockSize while nBlocks: f.write(nulBlock)
6
6010
by: Samuel M. Smith | last post by:
I have been playing around with a subclass of dict wrt a recipe for setting dict items using attribute syntax. The dict class has some read only attributes that generate an exception if I try to assign a value to them. I wanted to trap for this exception in a subclass using super but it doesn't happen. I have read Guido's tutorial on new style classes and Shalabh's tuturial on new style attributes and methods, and thought I understood...
6
2282
by: Joseph Geretz | last post by:
Writing an Outlook AddIn with C#. For the user interface within Outlook I'm adding matching pairs of Toolbar buttons and Menu items. All of the buttons and menu items are wired up to send events to the same method (aka delegate?). I use the Tag property within this method to determine what user action is taking place. Very simple: When adding toolbar button: tbButton.Click += new...
3
2639
by: Chuck Renner | last post by:
Please help! This MIGHT even be a bug in PHP! I'll provide version numbers and site specific information (browser, OS, and kernel versions) if others cannot reproduce this problem. I'm running into some PHP behavior that I do not understand in PHP 5.1.2. I need to parse the HTML from the following carefully constructed URI:
111
4692
by: Nate | last post by:
Hello, I am looking for a method to automatically declare variables in C. I'm not sure if there is a good way to do this, but I had something like this in mind... int i; for(i = 1; i < 4; i++){
7
2175
by: Michael Castleton | last post by:
When I open a csv or txt file with: infile = open(sys.argv,'rb').readlines() or infile = open(sys.argv,'rb').read() and then look at the first few lines of the file there is a carriage return + line feed at the end of each line - \r\n This is fine and somewhat expected. My problem comes from then writing
28
2570
by: v4vijayakumar | last post by:
#include <string> #include <iostream> using namespace std; int main() { string str; str.resize(5); str = 't';
0
9706
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
9579
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
10575
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...
1
10319
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,...
1
7616
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
6851
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
5520
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
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3816
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.