我如何跳过标题行并开始从第2行读取文件?
当前回答
如果切片可以在迭代器上工作……
from itertools import islice
with open(fname) as f:
for line in islice(f, 1, None):
pass
其他回答
f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
...
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()
如果切片可以在迭代器上工作……
from itertools import islice
with open(fname) as f:
for line in islice(f, 1, None):
pass
如果你想要第一行,然后你想对文件执行一些操作,这段代码将会很有帮助。
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
# Perform some operations
# Open a connection to the file
with open('world_dev_ind.csv') as file:
# Skip the column names
file.readline()
# Initialize an empty dictionary: counts_dict
counts_dict = {}
# Process only the first 1000 rows
for j in range(0, 1000):
# Split the current line into a list: line
line = file.readline().split(',')
# Get the value for the first column: first_col
first_col = line[0]
# If the column value is in the dict, increment its value
if first_col in counts_dict.keys():
counts_dict[first_col] += 1
# Else, add to the dict and set value to 1
else:
counts_dict[first_col] = 1
# Print the resulting dictionary
print(counts_dict)
推荐文章
- 有没有办法在python中做HTTP PUT
- “foo Is None”和“foo == None”之间有什么区别吗?
- 类没有对象成员
- Django模型“没有显式声明app_label”
- 熊猫能自动从CSV文件中读取日期吗?
- 在python中zip的逆函数是什么?
- 有效的方法应用多个过滤器的熊猫数据框架或系列
- 如何检索插入id后插入行在SQLite使用Python?
- 我如何在Django中添加一个CharField占位符?
- 如何在Python中获取当前执行文件的路径?
- 我如何得到“id”后插入到MySQL数据库与Python?
- super()失败,错误:TypeError "参数1必须是类型,而不是classobj"当父不继承对象
- Python内存泄漏
- 实现嵌套字典的最佳方法是什么?
- 如何在tensorflow中获得当前可用的gpu ?