如何检查文件路径与文件名
时间: 2023-04-09 08:01:47 浏览: 75
可以使用Python中的os.path模块来检查文件路径和文件名。具体方法是使用os.path.join()函数将路径和文件名拼接起来,然后使用os.path.exists()函数检查文件是否存在。例如:
import os
file_path = os.path.join('/path/to/directory', 'filename.txt')
if os.path.exists(file_path):
print('File exists')
else:
print('File does not exist')
相关问题
怎样通过文件路径获得文件名
可以使用Python内置的os模块中的`os.path.basename()`函数来获取文件路径中的文件名,示例代码如下:
```python
import os
file_path = "/path/to/file/example.txt"
file_name = os.path.basename(file_path)
print(file_name) # 输出:example.txt
```
其中,`file_path`为文件路径,`file_name`为获取到的文件名。
Java 通过文件路径获取文件名
可以使用Java的File类来获取文件名。以下是获取文件名的示例代码:
```java
File file = new File("C:\\Users\\UserName\\Documents\\example.txt");
String fileName = file.getName(); //获取文件名,结果为 "example.txt"
```
其中,File类的构造函数需要传入文件的绝对路径。getName()方法可以获取文件的名称。如果需要获取文件的完整路径,可以使用getPath()方法。