How to Read One Single Line of CSV Data in Python

CSV read specific row

You could use a list comprehension to filter the file like so:

with open('file.csv') as fd:
reader=csv.reader(fd)
interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)]
# now interestingrows contains the 28th and the 62th row after the header

How to read first N lines of a file?

Python 3:

with open("datafile") as myfile:
head = [next(myfile) for x in range(N)]
print(head)

Python 2:

with open("datafile") as myfile:
head = [next(myfile) for x in xrange(N)]
print head

Here's another way (both Python 2 & 3):

from itertools import islice

with open("datafile") as myfile:
head = list(islice(myfile, N))
print(head)

How can I open a csv file in python, and read one line at a time, without loading the whole csv file in memory?

with open(filename, "r") as file:
for line in file:
doanything()

Python is lazy whenever possible. File objects are generators and do not load the entire file but only one line at a time.

How to read a specific line number in a csv with pandas

One way could be to read part by part of your file and store each part, for example:

df1 = pd.read_csv("mydata.csv", nrows=10000)

Here you will skip the first 10000 rows that you already read and stored in df1, and store the next 10000 rows in df2.

df2 = pd.read_csv("mydata.csv", skiprows=10000 nrows=10000)
dfn = pd.read_csv("mydata.csv", skiprows=(n-1)*10000, nrows=10000)

Maybe there is a way to introduce this idea into a for or while loop.

Python: Extracting first element from each line of a CSV file

import csv

with open('Airports.txt', 'r') as f:
reader = csv.reader(f)
example_list = list(reader)

print(example_list)

OUTPUT:

[['JFK', 'John F Kennedy International', '5326', '5486'], ['ORY', 'Paris-Orly', '629', '379'], ['MAD', 'Adolfo Suarez Madrid-Barajas', '1428', '1151'], ['AMS', 'Amsterdam Schiphol', '526', '489'], ['CAI', 'Cairo International', '3779', '3584'], []]

Thank you for anyone who offered help, this is what I ended up settling on as it was what i was looking for, hope this helps anyone with any similar question.

Data being written in a single line in some csv file

For this Specific Code :

as contents is a list of items[lines]

contents = reader.getPage(7).extractText().split('\n')
for each in contents:
writer.writerow(each)

print(contents)

Try this and let me know.



Related Topics



Leave a reply



Submit