写一段python代码,按行读取文件,按tab分割,并写入新文件
时间: 2023-03-06 19:47:40 浏览: 89
with open('original_file.txt', 'r') as infile, open('new_file.txt', 'w') as outfile:
for line in infile:
columns = line.split('\t')
outfile.write('\t'.join(columns))
相关问题
python 读取csv到txt文件,列之间用tab分割
可以使用Python中的csv和os模块来实现这个功能,以下是示例代码:
```python
import csv
import os
# 读取csv文件
with open('input.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
# 创建输出文件
with open('output.txt', 'w') as txtfile:
# 遍历每一行
for row in reader:
# 将每一列用tab分割并写入输出文件
txtfile.write('\t'.join(row) + os.linesep)
```
其中,`input.csv`是要读取的csv文件名,`output.txt`是要输出的txt文件名,`os.linesep`是系统的换行符。
python读取txt文件,并且将每一行中的空格替换为tab
可以使用Python中的文件读写操作来实现这个功能。具体步骤如下:
1. 打开需要读取的txt文件,使用open函数即可:
```
file = open('filename.txt', 'r')
```
2. 读取文件内容,使用readlines函数,将每一行的内容以列表形式返回:
```
lines = file.readlines()
```
3. 遍历每一行,将空格替换为Tab,使用replace函数:
```
for i in range(len(lines)):
lines[i] = lines[i].replace(' ', '\t')
```
4. 将处理后的内容写入一个新的文件,使用open函数的w模式:
```
new_file = open('new_filename.txt', 'w')
new_file.writelines(lines)
```
5. 关闭文件:
```
file.close()
new_file.close()
```
完整代码如下:
```
file = open('filename.txt', 'r')
lines = file.readlines()
for i in range(len(lines)):
lines[i] = lines[i].replace(' ', '\t')
new_file = open('new_filename.txt', 'w')
new_file.writelines(lines)
file.close()
new_file.close()
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)