-2

I am a newby to Python. I have a source file which has 10 rows in it. Using Python I want to import 1 particular line to a new file.

Please let me know how I should proceed with this.

jeremy
  • 306
  • 4
  • 15

3 Answers3

2

You can use linecache if you know the number of line you are after:

import linecache
a_line = linecache.getline('/tmp/file.txt', 4)

# save it to new file
with open('new_file.txt', 'w') as f:
          f.write(a_line)
Marcin
  • 108,294
  • 7
  • 83
  • 138
1

You can write a "for" loop to count line by line, until you're at the line you want. After that, save a copy of that line onto a variable, in this case "stringTemp":

with open("file.txt", "r") as inputStream: # open a file.txt onto a stream variable
stringTemp = ""  # initialize an empty string, where you'll save the line you want
particularLineNumber = 3
count = 0      # a variable to keep count of which line you are on
for line in inputStream:   # "for each thing in the stream variable, save it onto "line"
    if count == particularLineNumber - 1: # if we are on the line we want...
        stringTemp = line                 # ... save it to stringTemp
    count = count + 1         # if we are NOT on the line we want, increase the counter


# ... write the variable stringTemp onto another file ...  

I'm assuming you want your line numbers as "1, 2, 3, 4, ... , 9, 10". If you decide to start at 0 ("0,1,2,3...10"), then remove the "- 1" on "if count == particularLineNumber - 1"

Kevin Hernandez
  • 494
  • 1
  • 5
  • 17
1

This will read the whole file at once:

with open(fname) as f:
    content = f.readlines()

With all the lines read, you can do whatever you like with it.

This will read the file one line at a time:

with open(fname) as f:
    for line in f:
        <do something with line>

This has been answered many times, though:

How to read large file, line by line in python

How do I read a file line-by-line into a list?

Community
  • 1
  • 1
jeremy
  • 306
  • 4
  • 15