others - python如何在文件夾打開所有文件


def FormatTXT():



 conhecimentos = os.listdir('U:/AutoCTE/Conhecimentos')



 for x in conhecimentos:


 with open(x,"r+") as f:


 old = f.read()


 text = old.replace("n","")


 f.seek(0)


 f.truncate(0)


 f.write(text)


 f.close()



但是,此函數返回以下錯誤:


FileNotFoundError: [Errno 2] No such file or directory: '20200119-170415-Conhecimento de Transporte.txt'



时间: 作者:

open的文件路徑缺少前綴U:/AutoCTE/Conhecimentos。由於你位於不同的目錄中,這些相對路徑不能工作


def FormatTXT():



 conhecimentos = os.listdir('U:/AutoCTE/Conhecimentos')



 for x in conhecimentos:


 with open('U:/AutoCTE/Conhecimentos/' + x,"r+") as f:


 old = f.read()


 text = old.replace("n","")


 f.seek(0)


 f.truncate(0)


 f.write(text)


 f.close()



有更好的方法可以做到這一點,例如,使用os.path模塊

作者:

首先,編寫一個函數來刪除解析文件文本,


def remove_end_lines(file_): 


"""


 remove"n" from file


"""


 with open(file_,"r+") as f:


 old = f.read()


 text = old.replace("n","")


 f.seek(0)


 f.truncate(0)


 f.write(text)


 f.close()




def FormatTXT(my_dir):



 original_dir = os.getcwd() # register original working dir


 conhecimentos = os.listdir(my_dir) # liste file in the dir


 os.chdir(my_dir) # change dir



 for file_ in conhecimentos: 


 remove_end_lines(file_)



 os.chdir(original_dir) # go back to original dir



第二選擇使用os.path.join()


def FormatTXT(my_dir):



 conhecimentos = os.listdir(my_dir) # liste all files in the dir



 for file_ in conhecimentos: 


 file_path = os.path.join(my_dir, file_) # create the file path by appening the file name to the directory path


 remove_end_lines(file_path)



如果有子目錄,並且想執行相同的操作,你應該使用os.walk()


def FormatTXT(my_dir):


 for dir_path, dir_name, files_name in os.walk(my_dir):


 # files_name is a list of all file in dir_path,


 if files_name: # if there is file in the current dir (the list is not empty)



 for file_ in files_names:


 file_path = os.path.join(my_dir, file_) 


 remove_end_lines(file_path)



作者:
...