python怎么删除文件名中的空格
时间: 2023-04-08 19:05:00 浏览: 176
可以使用Python中的replace()函数来删除文件名中的空格。具体代码如下:
import os
file_name = "example file.txt"
new_file_name = file_name.replace(" ", "")
os.rename(file_name, new_file_name)
这段代码会将文件名中的空格替换为空字符串,然后使用os.rename()函数将原文件名修改为新文件名。
相关问题
python 查找文件名中包含空格,換成別的
可以通过以下方式来实现:使用双引号将整个文件名括起来。例如:
```
import os
files = os.listdir('.')
for f in files:
if ' ' in f:
new_name = f.replace(' ', '_')
os.rename(f, new_name)
```
以上代码可以将当前目录下所有包含空格的文件名替换为下划线。
Python读取xml文件时文件名中有空格
如果你的xml文件名中有空格,你需要在文件名中将空格转义为"\ ", 或者将整个文件路径用引号括起来,例如:
```python
import xml.etree.ElementTree as ET
file_path = "path/to/my xml file.xml"
# 或者
file_path = "path/to/my\ xml\ file.xml"
tree = ET.parse(file_path)
root = tree.getroot()
```
这样就可以成功读取包含空格的xml文件了。
相关推荐
![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)