By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,104 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

Python newbie needs file I/O help

P: 2
Hi, newbie here, sorry. I have a couple of basic Python questions.

1) How do I open 'datafile' and skip to the ith line for reading? I have a loop counter i for this purpose. The data file is very long, and I'd like to read just 100 lines in at a time or so.

2) Is there any easy way to determine the length of a text file (in lines) besides opening the file, reading each line and using a counter?
Aug 20 '07 #1
Share this Question
Share on Google+
3 Replies


P: 2
Never mind, I think I just found a way around my problem. Better algorithm means I don't need to do this anymore. Thanks!
Aug 20 '07 #2

bartonc
Expert 5K+
P: 6,596
Hi, newbie here, sorry. I have a couple of basic Python questions.

1) How do I open 'datafile' and skip to the ith line for reading? I have a loop counter i for this purpose. The data file is very long, and I'd like to read just 100 lines in at a time or so.

2) Is there any easy way to determine the length of a text file (in lines) besides opening the file, reading each line and using a counter?
For future reference, file.readlines() returns a Python list object. So:
Expand|Select|Wrap|Line Numbers
  1. f = open("fileName")
  2. linesList = f.readlines()
  3. f.close()
  4. nLines = len(linesList)
  5. nth = 5
  6. nthLine = linesList[nth]
Aug 20 '07 #3

Expert 100+
P: 511
for very large files, you might want to iterate through the file
Expand|Select|Wrap|Line Numbers
  1. ...
  2. for num,line in enumerate(open("file")):
  3.      if num == 9:
  4.          print "skip line 10"
  5.      #do+something
  6.  
Aug 20 '07 #4

Post your reply

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