簡體   English   中英

檢查特定目錄中是否存在 txt 文件?

[英]check if a txt file exist in a specific directory or not?

我試圖找出指定目錄中是否存在名稱為“newfile”的 txt 文件,如果不存在,則創建一個新的 txt 文件

import os.path
if (os.path.exists("newfile.txt") == False):
    open("count.txt", "w")

但它不起作用,因為我無法使用此代碼訪問當前或指定的導演。

您可以使用glob來定位目錄。

import glob

file_path = glob.glob('../your/file_directory/*')
if "count.txt" not in file_path:
    with open('../your/file_directory/count.txt', 'w') as f:
        f.write('Create new text file')

import inspect
import os

module_path = inspect.getfile(inspect.currentframe())
module_dir = os.path.realpath(os.path.dirname(module_path))
os.chdir(module_dir) # set working directory to where file is

if not os.path.exists("C:\\absolute\\directory\\newfile.txt"):
    open("count.txt", "w")

您可以將路徑替換為 unix 樣式目錄。

解決 1:

import os.path

file = 'yourpath\file_to_check.txt'     # 예제 Textfile

if os.path.isfile(file):
  print("Yes. it is a file")
elif os.path.isdir(file):
  print("Yes. it is a directory")
elif os.path.exists(file):
  print("Something exist")
else :
  print("Nothing")

解決2:

from pathlib import Path

my_file = Path("your_path\file_to_check.txt") # This way only works in windows os
if my_file.is_file():
  print("Yes it is a file") 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM