python读取txt文件,以空格为分隔读取为列表
时间: 2024-02-13 07:04:55 浏览: 207
可以使用Python内置的`open()`函数来读取txt文件。具体步骤如下:
1. 使用`open()`函数打开txt文件,并指定打开模式为`r`(只读模式)。
```python
file = open('file.txt', 'r')
```
2. 使用`read()`方法读取文件内容,并将其存储到变量中。
```python
content = file.read()
```
3. 关闭文件,释放资源。
```python
file.close()
```
4. 将读取到的内容按空格分割,并存储到列表中。
```python
word_list = content.split(' ')
```
完整代码示例:
```python
file = open('file.txt', 'r')
content = file.read()
file.close()
word_list = content.split(' ')
print(word_list)
```
注意:在使用`open()`函数打开文件时,应该使用文件的绝对路径或相对路径。另外,如果文件中的单词之间不是用空格分隔,可以将`split()`方法中的参数改为其他分隔符。
相关问题
python读取txt文件,以空格为分隔读取为列表,一行为一个列表
可以使用Python内置的`open()`函数来读取txt文件。具体步骤如下:
1. 使用`open()`函数打开txt文件,并指定打开模式为`r`(只读模式)。
```python
file = open('file.txt', 'r')
```
2. 使用`readlines()`方法读取文件内容,并将其存储到变量中。
```python
content = file.readlines()
```
3. 关闭文件,释放资源。
```python
file.close()
```
4. 遍历读取到的每一行,将每一行按空格分割,并存储到一个列表中。
```python
word_list = []
for line in content:
line_list = line.strip().split(' ')
word_list.append(line_list)
```
完整代码示例:
```python
file = open('file.txt', 'r')
content = file.readlines()
file.close()
word_list = []
for line in content:
line_list = line.strip().split(' ')
word_list.append(line_list)
print(word_list)
```
注意:在使用`open()`函数打开文件时,应该使用文件的绝对路径或相对路径。另外,如果文件中的单词之间不是用空格分隔,可以将`split()`方法中的参数改为其他分隔符。
python 读取txt 并以空格分隔
可以使用 Python 的 open() 函数打开 txt 文件,然后使用 split() 函数以空格为分隔符将文本内容分隔成列表。示例代码如下:
```
with open('file.txt', 'r') as f:
content = f.read()
words = content.split(' ')
print(words)
```
其中,'file.txt' 是你要读取的 txt 文件名,'r' 表示以只读模式打开文件。读取文件内容后,使用 split(' ') 函数将文本内容以空格为分隔符分隔成列表,存储在 words 变量中。最后,使用 print() 函数输出列表内容。
阅读全文
相关推荐
















