如何在python中未命名为csv的csv文件中打印特定行?
我应该写一个函数专门做这个如何在python中未命名为csv的csv文件中打印特定行?,python,Python,我应该写一个函数专门做这个 def get_customer_record(file_handle, n): """ ------------------------------------------------------- Find the n-th record in a comma-delimited sequential file. Records are numbered starting with 0. Use: result = get_
def get_customer_record(file_handle, n):
"""
-------------------------------------------------------
Find the n-th record in a comma-delimited sequential file.
Records are numbered starting with 0.
Use: result = get_customer_record(file_handle, n)
-------------------------------------------------------
Parameters:
file_handle - file to search (file - open for reading)
n - the number of the record to return (int > 0)
Returns:
result - a list of the fields of the n-th record if it exists,
an empty list otherwise (list)
-------------------------------------------------------
"""
这是文件
customers.txt
代码
list = []
file_handle = open('customers.txt', 'r+', encoding="utf-8")
line = file_handle.readline(n)
list.append(line.strip(','))
file_handle.close()
return list
从语法上看,不清楚是将行作为字符串返回,还是将字段拆分为,。我假设是单行线 python readline函数不获取索引,它只是从文件中读取下一行。下面我使用了readlines注释s,它读取文件中的所有行。如果您的文件很大,那么这将不会如此高效 另外,对越界n进行一点错误处理有助于:
显然,这段代码假设n被索引为0->n-1。一个简单的解决方案是使用以下方法迭代文件:
到目前为止你都试了些什么?它以什么方式不工作?欢迎使用堆栈溢出!请阅读,环顾四周,通读,特别是如果您遇到特定问题,请进行彻底的研究,在此处进行彻底的搜索,如果您仍然被困,请发布您的代码和问题的描述。另外,记住要包括。人们将乐于帮助欢迎来到SO,我们是一个志愿者社区,帮助回答代码中的问题。不幸的是,这里没有代码,我们不写程序。请尝试自己回答这个问题,如果遇到任何问题,请回来。在询问之前,不要害怕搜索您的问题,也许阅读python的CSV模块或者python的输入和输出语法会有所帮助-@Kingsley list=[]文件\u handle=open'customers.txt',r+',encoding=utf-8 line=file\u handle.readlinelist.appendline.strip','file_handle.close return list我尝试过这样做,下面是我测试文件中的内容。从函数导入get_customer_record file_handle=open'customers.txt',r+,encoding=utf-8 n=intinput result=get_customer_record file_handle,n printlist非常感谢您的帮助,我唯一的问题是为什么使用3?在行字段中=获取。。。。。感谢you@DavidEnjugu我用3作为测试数字,没有特别的原因。但是FWIW我也测试了0,5,50和-4。
list = []
file_handle = open('customers.txt', 'r+', encoding="utf-8")
line = file_handle.readline(n)
list.append(line.strip(','))
file_handle.close()
return list
def get_customer_record(file_handle, n):
lines = file_handle.readlines()
if (n >= 0 and n < len(lines)):
return lines[n] # or n-1?
else:
return None
file_handle = open( 'customers.txt', 'r+', encoding="utf-8" )
fields = get_customer_record( file_handle, 3 )
print( str( fields ) )
def get_customer_record(file_handle, n):
if (n >= 0):
line = file_handle.readline()
while (n > 0):
line = file_handle.readline()
if (line == ''):
line = None
break # end of file
n -= 1
return line
else:
return None
from csv import reader
def get_customer_record(file_handle, n):
with open(file=file_handle) as csvfile:
csv_reader = reader(csvfile)
return next((line for row, line in enumerate(csv_reader) if row == n), [])
print(get_customer_record(file_handle='customer.csv', n=3))
# ['43564', 'Weilin', 'Zhao', '450.25', '1998-01-03']
print(get_customer_record(file_handle='customer.csv', n=5))
# []