os.path.exists()将创建该文件

时间:2015-06-29 22:44:14

标签: python macos python-2.7

每次运行程序时,我都会使用以下代码将一些日志写入新文件。但似乎os.path.exists()每次运行时都会创建所有文件。我在OS X 10.10.3上使用mac。

.exists()

如果我在终端中运行python脚本,即" python ./that_code.py"或者在IDE中,.exists()将创建文件。但是只需在IPython中运行MediaPlayer soundofletter; int indeks=0; String[] letter = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; int [] sound = {R.raw.a , R.raw.b , R.raw.c , R.raw.d , R.raw.e , R.raw.f , R.raw.g , R.raw.h , R.raw.i , R.raw.j , R.raw.k , R.raw.l , R.raw.m , R.raw.n , R.raw.o , R.raw.p , R.raw.q , R.raw.r , R.raw.s , R.raw.t , R.raw.u , R.raw.v , R.raw.w , R.raw.x , R.raw.y , R.raw.z}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.lihathuruf); Gallery g = (Gallery) findViewById(R.id.gallery1); g.setAdapter(new ImageAdapter(this)); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) { Toast.makeText(LihatHuruf.this, "" + letter[position], Toast.LENGTH_SHORT).show(); } }); } public ImageAdapter(Context c) { mContext = c; TypedArray a = obtainStyledAttributes(R.styleable.Gallery1); mGalleryItemBackground = a.getResourceId( R.styleable.Gallery1_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { return mImageIds.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); i.setImageResource(mImageIds[position]); i.setLayoutParams(new Gallery.LayoutParams(250, 300)); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setBackgroundResource(mGalleryItemBackground); return i; } 就不会创建文件。

1 个答案:

答案 0 :(得分:2)

你完全正确

for idx in range(0, 100):
    if os.path.exists(str(idx) + ".out.txt"):
        continue
    else:
        output_file = open(str(idx) + ".out.txt", "w")

...创建所有相关文件。您完全错误它是os.path.exists()行。

        output_file = open(str(idx) + ".out.txt", "w")

...创建为打开而打开的文件。将该行替换为pass,或者只是完全删除else子句,您将看到不再创建该项。

顺便说一下 - 在Go中,这种模式被认为是不好的做法,并且有人想要确保存在这些数百个文件,建议无条件地打开它们进行写入,而不检查它们是否先前存在过。这种方法避免了竞争条件 - 如果文件的存在在os.path.exists()电话和open()之间发生变化,会发生什么情况,并且还会减少stat()次来电。