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.
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.
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"
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: