Skip to main content
 首页 » 编程设计

python之python 中的文件名处理错误

2025年05月04日11exmyth

显示此错误的最小工作示例:

from os import listdir, getcwd 
from os.path import isfile, join, realpath, dirname 
import csv 
 
def gd(mypath, myfile): 
    # Obtain the number of columns in the data file 
    with open(myfile) as f: 
        reader = csv.reader(f, delimiter=' ', skipinitialspace=True) 
        for i in range(20): 
            row_20 = next(reader) 
        # Save number of clumns in 'num_cols'. 
        num_cols = len(row_20) 
        return num_cols 
 
mypath = realpath(join(getcwd(), dirname(__file__))) 
 
# Iterate through all files. Stores name of file in 'myfile'. 
for myfile in listdir(mypath): 
 
    if isfile(join(mypath,myfile)) and (myfile.endswith('.dat')): 
        num_cols = gd(mypath, myfile) 
 
print(num_cols) 

我在该文件夹中有一个名为“data.dat”的文件,python 返回错误:

----> 9     with open(myfile) as f: 
.... 
IOError: [Errno 2] No existe el archivo o el directorio: u'data.dat' 

转换为没有文件或目录:u'data.dat'。

为什么 u 被添加在文件名的开头,我如何获得正确解析文件名的代码?

请您参考如下方法:

u只是表示它是一个unicode字符串,与问题无关。

找不到文件,因为您没有在文件名前面添加 mypath - 尝试 with open(join(mypath, myfile)) as f: