我有一段这样的代码:
if __name__ == '__main__':
taxids = [1204725, 2162, 1300163, 420247]
desired_ranks = ['kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species']
path = 'taxids.csv'
main(taxids, desired_ranks, path)
我有一个文件,其中包含这些数字(以及更多数字),每个数字都用这样的一行隔开。 myFile.csv包含:
1204725
2162
1300163
420247
我想知道如何读入文件来替换'taxids'变量?
[已解决]工作代码如下。
with open('justTaxidsCOG0202.csv', 'r') as file:
stringtaxids = file.read().replace('\n', ', ')
taxids = stringtaxids.split(', ')
答案 0 :(得分:1)
在documentation中,如果要将文件的所有行读入列表,则可以使用list(f)
或f.readlines()
。这种方法的缺点是每次滑行结束时都会获得换行符。另一种处理方法如下所述。
with open('myFile.csv', 'r') as file:
#this method includes the newlines (\n) at the end of each taxid
taxids = file.readlines()
#this method strips those newlines, still giving you a list
#taxids = file.read().splitlines()