python写入文件加逗号
时间: 2023-10-16 15:31:12 浏览: 168
如果你想在 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
```
阅读全文
相关推荐
















