如何从第二行开始将文本文件读入Python中的字符串变量?

时间:2015-06-11 16:53:26

标签: python string list python-2.7 readfile

我使用以下代码段来读取python中的文件

<?php $form = ActiveForm::begin(); ?>
 <?= $form->field($model, 'item_id')->dropDownList($items) ?>
<?php ActiveForm::end(); ?>

但是,我需要将整个文件(除了第一行)作为字符串读入变量file = open("test.txt", "rb") data=file.readlines()[1:] file.close print data

实际上,当我的文件内容为data时,我的变量包含列表['testtesttest']。

如何将文件读入字符串?

我在Windows 7上使用python 2.7。

1 个答案:

答案 0 :(得分:2)

解决方案非常简单。您只需要使用这样的with ... as结构,从第2行开始读取,然后将返回的列表加入到字符串中。在这个特定的例子中,我使用""作为连接分隔符,但您可以使用您喜欢的任何内容。

with open("/path/to/myfile.txt", "rb") as myfile:
     data_to_read = "".join(myfile.readlines()[1:])
     ...

使用with ... as构造的优势在于文件已明确关闭,您无需致电myfile.close()