基本挑战
这是一个CSV文件的内容,"my_file.csv" ,用于我们下面的代码片断。
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000
如果你把这个CSV文件以表格形式显示出来,它看起来像这样。
| 名称 | 工作 | 年龄 | 收入 |
|---|---|---|---|
| 爱丽丝 | 程序员 | 23 | 110000 |
| 鲍勃 | 行政人员 | 34 | 90000 |
| 卡尔 | 销售人员 | 45 | 50000 |
基本问题是在不改变内容的情况下,将CSV文件"my_file.csv" ,转换成一个新的TXT文件"my_file.txt" 。
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000
我们从探索这个基本挑战开始,然后通过改变分隔符和使用Pandas来访问各个列来建立。
但首先要做的是。 如何在不改变内容的情况下将CSV文件转换为TXT文件?
方法一:CSV转TXT不改变内容
如果你想保持CSV文件中的内容(包括分隔符',' )不被修改,转换很简单:读取.csv 文件并将其内容写入一个新的.txt 文件中,使用 [open()](https://blog.finxter.com/python-open-function/), [read()](https://blog.finxter.com/python-read-binary-file/),和 [write()](https://blog.finxter.com/python-one-liner-write-string-to-file/)函数将其内容写入一个新的,而无需导入任何库。
换句话说,执行以下三个步骤,将CSV文件不加修改地写成TXT文件。
- 在阅读模式下打开CSV文件,在写作模式下打开TXT文件。
- 读取CSV文件并将其存储在一个变量中。
- 将内容写进TXT文件。
这里是解决我们基本挑战的代码片段。
# 1. Open the CSV file in reading mode and the TXT file in writing mode
with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out:
# 2. Read the CSV file and store in variable
content = f_in.read()
# 3. Write the content into the TXT file
f_out.write(content)
鲜为人知的事实:如果你用逗号把它们分开,Python 允许在上下文管理器( 开头一行) 中有with 多个表达式。
.csv 和.txt 文件的内容是相同的。
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000
到目前为止,一切都很好。但如果你有一个稍微不同的问题呢。
方法2:CSV到TXT的空位定界符
挑战:如何在Python中把CSV文件转换成TXT文件,把分隔符',' 替换为空位' '?
例子。将下面的文件'my_file.csv'...
Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000
...转换成这个文件'my_file.txt'...
Name Job Age Income
Alice Programmer 23 110000
Bob Executive 34 90000
Carl Sales 45 50000
下面是这个难题的简单解决方案。
如果你想在新的TXT文件中把分隔符',' 改为空字符串' ' ,请读取.csv 文件,并使用 、 和 函数把它的内容写入一个新的.txt 文件中。 [open()](https://blog.finxter.com/python-open-function/), [read()](https://blog.finxter.com/python-read-binary-file/), [string.replace()](https://blog.finxter.com/python-string-replace-2/)和 [write()](https://blog.finxter.com/python-one-liner-write-string-to-file/)函数来读取文件并将其内容写入新的 文件,而不需要导入任何库。
要在Python中把CSV转换成TXT文件,请执行以下步骤。
- 以阅读模式打开CSV文件,以书写模式打开TXT文件。
- 将CSV文件读成一个字符串。
- 通过用空字符串
' '替换所有出现的分隔符','来创建一个新字符串。 - 把内容写进TXT文件。
with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out:
content = f_in.read().replace(',', ' ')
f_out.write(content)
到目前为止,一切都很好。但是在Python中,总是有很多方法来解决一个问题。让我们来看看之前使用的无库方法的一个强大的替代方法。
方法 3:使用潘达斯将 CSV 转为 TXT
假设你已经在本地环境中安装了pandas,你可以在Python pandas中通过以下四个步骤把CSV写成TXT文件。
- 导入
[pan](https://blog.finxter.com/pandas-quickstart/)[d](https://blog.finxter.com/pandas-quickstart/)[as](https://blog.finxter.com/pandas-quickstart/)库。 - 将CSV文件读入一个DataFrame,使用
[pd.read_csv()](https://blog.finxter.com/read-and-write-flat-files-with-pandas/). - 使用内建的函数将DataFrame转换为字符串。
[str()](https://blog.finxter.com/python-str-function/)函数将DataFrame转换成字符串。 - 使用函数的文件参数将字符串打印到一个文件中。
[print()](https://blog.finxter.com/python-print/)函数,例如。
下面是基本的Python例子。
import pandas as pd
df = pd.read_csv('my_file.csv')
content = str(df)
print(content, file=open('my_file.txt', 'w'))
鲜为人知的事实:Python的 [print()](https://blog.finxter.com/python-print/)函数允许你直接 将一个字符串 写入一个文件 对象,如果你使用file 参数,如代码片段所示。
前面的代码片断的输出如下。
Name Job Age Income
0 Alice Programmer 23 110000
1 Bob Executive 34 90000
2 Carl Sales 45 50000
很漂亮,不是吗?
让我们来看看本教程中涉及的 "CSV转TXT "问题的最后一个变体。
方法四:使用Pandas将CSV列或行转为TXT
如何使用Python Pandas将CSV文件中的一个或多个单独的列或行写入TXT文件中?
- 导入
[pan](https://blog.finxter.com/pandas-quickstart/)[d](https://blog.finxter.com/pandas-quickstart/)[as](https://blog.finxter.com/pandas-quickstart/)库。 - 通过使用以下方法将CSV文件读入一个DataFrame中
[pd.read_csv()](https://blog.finxter.com/read-and-write-flat-files-with-pandas/). - 使用Pandas索引或切片,从DataFrame中选择要写进TXT文件的列或行。
- 调用
df.to_string(),以人类可读的方式将DataFrame转换为一个字符串。 - 使用函数的文件参数将字符串打印到一个文件中。
[print()](https://blog.finxter.com/python-print/)函数,将字符串打印到一个文件中。
import pandas as pd
df = pd.read_csv('my_file.csv')
content = str(df['Name'])
print(content, file=open('my_file.txt', 'w'))
在一个新文件中的内容'my_file.txt' 。
0 Alice
1 Bob
2 Carl
当然,你也可以像这样选择单个行或多个列。
import pandas as pd
df = pd.read_csv('my_file.csv')
content = df['Name'][:2].to_string()
print(content, file=open('my_file.txt', 'w'))
新文件的内容'my_file.txt' 显示,由于前面代码片断中的切片操作[:2] ,只有前两行被选中。
0 Alice
1 Bob
完成了!你已经赢得了一些编程的乐趣。
程序员的幽默
**Question:** How did the programmer ***die*** in the shower? ☠ ❗ **Answer**: They read the shampoo bottle instructions: ***Lather. Rinse. Repeat.***
结语
我希望你喜欢阅读这篇文章并学到一些新东西。欢迎加入我们的电子邮件通讯,提供免费的小抄和每周的 Python 教程。