nums=filename.split(('_')[1:])
时间: 2024-01-31 15:04:17 浏览: 30
这段代码会报错,因为split()方法的参数应该是一个字符串,而('_')[1:]并不是一个字符串。
如果你想要将文件名按照下划线'_'进行分割,并获取从第二个下划线后面的所有内容,可以使用以下代码:
```python
nums = filename.split('_')[1:]
```
这段代码中,我们首先使用split()方法将文件名按照下划线进行分割,然后通过索引[1:]获取从第二个下划线后面的所有内容,最终将其赋值给变量nums。这样就可以正确地获取文件名中的数字部分了。
相关问题
uni.request({ url: config.baseUrl + '/API/Task/getToken', method: 'GET', success(res) { that.baseUrl = res.data.domain that.token = res.data.token; // 获取到 token 后再进行上传 that.imgList.push(e.tempFilePaths[0]); const fileName = e.tempFilePaths[0].substr(e.tempFilePaths[0] .lastIndexOf('/') + 1); // 获取文件名 const fileExt = fileName.substr(fileName.lastIndexOf('.') + 1) .toLowerCase(); // 获取文件拓展名,并转换为小写 const today = new Date().toISOString().slice(0, 10); // 获取当天日期,格式为 yyyy-mm-dd const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; const day = now.getDate(); const hour = now.getHours(); const minute = now.getMinutes(); const currentDateTime = ${year}-${month}-${day}-${hour}:${minute}:00; var nums = []; that.uploadCount++; // 上传次数加一 const newFileName = currentDateTime + '' + that.uploadCount + '.' + fileExt; // 生成新的文件名,以上传次数为前缀 const path = that.fromData.c_name + '/' + that.fromData.a_name + '/' + that.fromData.m_name + '/' + that.fromData.mold + '/' + that.fromData.m_title + '/' + that.fromData.r_name + '-' + that.uploadCount + '/' + that.fromData.o_name + '/' + today; const key = path + '/' + newFileName that.imgData.push(key) uni.uploadFile({ url: 'https://upload-z1.qiniup.com', filePath: e.tempFilePaths[0], name: 'file', formData: { token: res.data.token, key: path + '/' + newFileName // 将路径和文件名拼接起来 }, success(res) { const data = JSON.parse(res.data); const key = data.key const parts = key.split("."); const KeynewName = parts.slice(0, -1).join(".") + ".jpg"; that.baseList.push(that.baseUrl + KeynewName) that.Keyname.push(KeynewName) for (var i = 0; i < that.Keyname.length; i++) { var num = that.Keyname[i].split('/').slice(-1)[0].split('.')[0].split('')[1]; nums.push(num); } console.log('存在的文件名:'+nums) }, fail(erro) { console.log(erro); } }); }, fail(err) { console.log("获取 Token 失败:", err); } });我想让这里的uploadCount先判断nums中存在哪些,uploadCount只能为1,2,3 如果nums存在1,2那么uploadCount只能为3
可以在上传之前先判断 nums 数组中是否存在 1 和 2,并将结果保存在两个变量中,比如 hasOne 和 hasTwo。然后根据这两个变量来判断 uploadCount 的值,如果 hasOne 和 hasTwo 都为 true,那么 uploadCount 只能为 3,否则 uploadCount 可以为 1、2 或 3。可以参考下面的代码:
```
// 判断 nums 数组中是否存在 1 和 2
var hasOne = nums.includes('1');
var hasTwo = nums.includes('2');
// 根据 hasOne 和 hasTwo 来判断 uploadCount 的值
if (hasOne && hasTwo) {
that.uploadCount = 3;
} else {
that.uploadCount = Math.floor(Math.random() * 2) + 1;
}
```
这段代码中,使用了 includes 方法来判断 nums 数组中是否存在 1 和 2,如果存在则将 hasOne 和 hasTwo 设置为 true,否则为 false。然后根据 hasOne 和 hasTwo 的值来判断 uploadCount 的值,如果都为 true,则 uploadCount 只能为 3,否则可以随机生成 1 或 2。
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'P_F_100_1.bmp' -> '0001_0000'
这个错误通常是由于指定的文件不存在或者文件名有误导致的。
在你的代码中,出现这个错误的原因可能是在遍历文件列表时,出现了文件名不存在或者文件名拼写错误的情况。建议你检查一下文件名是否正确,以及文件是否存在于指定的路径中。
同时,你也可以在代码中添加一些异常处理机制,以避免出现这个错误。例如,在使用`os.rename()`方法进行文件重命名时,可以使用`try...except...`语句进行异常处理,避免由于文件不存在而导致程序崩溃:
```python
import os
for filename in os.listdir('.'):
if filename.startswith('P_'):
nums = filename.split('_')[1:]
new_filename = f'{int(nums[0]):04d}_{int(nums[1]):04d}'
try:
os.rename(filename, new_filename)
except FileNotFoundError:
print(f'文件{filename}不存在')
```
在上述代码中,我们使用`try...except...`语句对`os.rename()`方法进行了异常处理。如果文件不存在,`os.rename()`方法会抛出`FileNotFoundError`异常,我们在`except`分支中捕获这个异常并输出提示信息,避免程序崩溃。