python输出没有逗号,写入txt就有逗号
时间: 2024-02-05 09:45:05 浏览: 35
这可能是由于不同的输出方式引起的。在Python中,通过print语句输出时,默认情况下,Python会在每个元素之间添加一个空格,并在最后一个元素后添加一个换行符。但是,当你将输出写入到txt文件中时,它会以字符串形式写入,因此所有的逗号和空格都会被保留。
如果你想在写入txt文件时去掉逗号和空格,可以使用字符串的join方法,将列表中的元素连接在一起,然后写入文件。例如:
```
# 示例代码
my_list = ["apple", "banana", "cherry"]
with open("output.txt", "w") as f:
f.write(' '.join(my_list))
```
这将会把列表中的每个元素连接起来,用空格分隔,并写入到output.txt文件中。
相关问题
用python将列表写入txt以逗号分隔
可以使用Python的csv模块,可以将列表以逗号分隔的形式写入txt文件,例如:import csv with open('file.txt', 'w', newline='') as f: writer = csv.writer(f) writer.writerows(list)
python写入文件加逗号
如果你想在 Python 中将字符串写入文件并在每个字符串之间添加逗号,可以尝试以下代码:
```python
# 打开文件
with open('filename.txt', 'w') as file:
# 要写入的字符串
strings = ['hello', 'world', 'python']
# 将每个字符串写入文件并在其后面添加逗号
for string in strings:
file.write(string + ',')
```
这将会在 "filename.txt" 文件中写入以下内容:
```
hello,world,python,
```
请注意,在最后一个字符串后也会添加逗号。如果你不想要这个逗号,可以在循环结束后删除它。你可以使用 `rstrip()` 方法删除字符串末尾的逗号,如下所示:
```python
# 打开文件
with open('filename.txt', 'w') as file:
# 要写入的字符串
strings = ['hello', 'world', 'python']
# 将每个字符串写入文件并在其后面添加逗号
for string in strings:
file.write(string + ',')
# 删除最后一个逗号
file.seek(file.tell() - 1)
file.truncate()
```
这将会在 "filename.txt" 文件中写入以下内容:
```
hello,world,python
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)