python 删除txt倒数第三行文本 最后的字符“,”
时间: 2023-09-16 09:10:02 浏览: 42
好的,以下是处理文件的 Python 代码,会将指定文件中倒数第三行的逗号删除。
```python
def remove_comma(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
if len(lines) >= 3:
lines[-3] = lines[-3].rstrip(',') + '\n'
with open(file_path, 'w') as file:
file.writelines(lines)
file_path = "your_file_path"
remove_comma(file_path)
```
请注意将代码中的 `your_file_path` 改为您实际的文件路径。执行代码后,指定文件中倒数第三行的逗号应该已经被删除了。
相关问题
python 删除txt倒数第三行文本 最末尾的字符
好的,以下是处理文件的 Python 代码,会将指定文件中倒数第三行末尾的字符删除。
```python
def remove_last_char(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
if len(lines) >= 3:
lines[-3] = lines[-3][:-1] + '\n'
with open(file_path, 'w') as file:
file.writelines(lines)
file_path = "your_file_path"
remove_last_char(file_path)
```
请注意将代码中的 `your_file_path` 改为您实际的文件路径。执行代码后,指定文件中倒数第三行末尾的字符应该已经被删除了。
python删除txt倒数第3行字符串的最后1个字符
如果你想要删除txt文件中倒数第3行的最后一个字符,可以使用类似的方法,修改一下代码:
``` python
with open('example.txt', 'r') as f:
lines = f.readlines()
with open('example.txt', 'w') as f:
for i, line in enumerate(lines):
if i != len(lines) - 3: # 不是倒数第三行
f.write(line)
else:
f.write(line[:-1]) # 倒数第三行去掉最后一个字符
```
上面的代码中,我们使用了类似的方法读取文件中的所有行,并将其存储在`lines`列表中。然后,我们使用一个`for`循环遍历所有行,如果不是倒数第三行,就将这一行写回文件中。如果是倒数第三行,就将这一行的最后一个字符去掉再写回文件中。这样就可以删除倒数第三行的最后一个字符了。
相关推荐
![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)