标签归档:file-io

使用Python将列表写入文件

问题:使用Python将列表写入文件

因为writelines()不插入换行符,这是将列表写入文件的最干净的方法吗?

file.writelines(["%s\n" % item  for item in list])

似乎会有一种标准的方法…

Is this the cleanest way to write a list to a file, since writelines() doesn’t insert newline characters?

file.writelines(["%s\n" % item  for item in list])

It seems like there would be a standard way…


回答 0

您可以使用循环:

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

在Python 2中,您也可以使用

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item

如果您热衷于单个函数调用,请至少移除方括号[],以使要打印的字符串一次生成一个(一个genexp而不是一个listcomp)-没有理由占用所有需要的内存具体化整个字符串列表。

You can use a loop:

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

In Python 2, you can also use

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item

If you’re keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) — no reason to take up all the memory required to materialize the whole list of strings.


回答 1

您将如何处理该文件?该文件是否存在于人类或具有明确互操作性要求的其他程序中?

如果您只是尝试将列表序列化到磁盘以供同一python应用程序稍后使用,则应该对列表进行腌制

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

读回:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?

If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.

import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)

To read it back:

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

回答 2

比较简单的方法是:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

您可以使用生成器表达式来确保项目列表中的所有项目都是字符串:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

请记住,所有itemlist列表都必须在内存中,因此,请注意内存消耗。

The simpler way is:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(itemlist))

You could ensure that all items in item list are strings using a generator expression:

with open("outfile", "w") as outfile:
    outfile.write("\n".join(str(item) for item in itemlist))

Remember that all itemlist list need to be in memory, so, take care about the memory consumption.


回答 3

使用Python 3Python 2.6+语法:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

这是与平台无关的。它还以换行符结束最后一行,这是UNIX的最佳实践

从Python 3.6开始,"{}\n".format(item)可以用f字符串替换:f"{item}\n"

Using Python 3 and Python 2.6+ syntax:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

Starting with Python 3.6, "{}\n".format(item) can be replaced with an f-string: f"{item}\n".


回答 4

还有另一种方式。使用simplejson(在python 2.6中包含为json)序列化为json

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

如果您检查output.txt:

[1、2、3、4]

这很有用,因为语法是pythonic的,它是人类可读的,并且可以由其他语言的其他程序读取。

Yet another way. Serialize to json using simplejson (included as json in python 2.6):

>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()

If you examine output.txt:

[1, 2, 3, 4]

This is useful because the syntax is pythonic, it’s human readable, and it can be read by other programs in other languages.


回答 5

我认为探索使用genexp的好处会很有趣,所以这是我的看法。

问题中的示例使用方括号创建临时列表,因此等效于:

file.writelines( list( "%s\n" % item for item in list ) )

它不必要地构造了将要写出的所有行的临时列表,这可能会消耗大量内存,具体取决于列表的大小以及输出的详细str(item)程度。

放下方括号(相当于删除list()上面的包装调用)将改为将临时生成器传递给file.writelines()

file.writelines( "%s\n" % item for item in list )

该生成器将item按需创建换行终止的对象表示形式(即,当对象被写出时)。这样做有几个方面的好处:

  • 内存开销很小,即使列表很大
  • 如果str(item)速度较慢,则在处理每个项目时文件中都有可见的进度

这样可以避免出现内存问题,例如:

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(通过,我通过将Python的最大虚拟内存限制为〜100MB触发了此错误ulimit -v 102400)。

一方面,此方法实际上并没有比原始方法快:

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(Linux上的Python 2.6.2)

I thought it would be interesting to explore the benefits of using a genexp, so here’s my take.

The example in the question uses square brackets to create a temporary list, and so is equivalent to:

file.writelines( list( "%s\n" % item for item in list ) )

Which needlessly constructs a temporary list of all the lines that will be written out, this may consume significant amounts of memory depending on the size of your list and how verbose the output of str(item) is.

Drop the square brackets (equivalent to removing the wrapping list() call above) will instead pass a temporary generator to file.writelines():

file.writelines( "%s\n" % item for item in list )

This generator will create newline-terminated representation of your item objects on-demand (i.e. as they are written out). This is nice for a couple of reasons:

  • Memory overheads are small, even for very large lists
  • If str(item) is slow there’s visible progress in the file as each item is processed

This avoids memory issues, such as:

In [1]: import os

In [2]: f = file(os.devnull, "w")

In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop

In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
...
MemoryError

(I triggered this error by limiting Python’s max. virtual memory to ~100MB with ulimit -v 102400).

Putting memory usage to one side, this method isn’t actually any faster than the original:

In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop

In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop

(Python 2.6.2 on Linux)


回答 6

因为我很懒…

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

Because i’m lazy….

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

回答 7

将列表序列化为带有逗号分隔值的文本文件

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

Serialize list into text file with comma sepparated value

mylist = dir()
with open('filename.txt','w') as f:
    f.write( ','.join( mylist ) )

回答 8

一般来说

以下是writelines()方法的语法

fileObject.writelines( sequence )

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

参考

http://www.tutorialspoint.com/python/file_writelines.htm

In General

Following is the syntax for writelines() method

fileObject.writelines( sequence )

Example

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]

# Write sequence of lines at the end of the file.
line = fo.writelines( seq )

# Close opend file
fo.close()

Reference

http://www.tutorialspoint.com/python/file_writelines.htm


回答 9

file.write('\n'.join(list))
file.write('\n'.join(list))

回答 10

with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")
with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")

回答 11

如果您使用的是python3,则还可以使用print函数,如下所示。

f = open("myfile.txt","wb")
print(mylist, file=f)

You can also use the print function if you’re on python3 as follows.

f = open("myfile.txt","wb")
print(mylist, file=f)

回答 12

你为什么不尝试

file.write(str(list))

Why don’t you try

file.write(str(list))

回答 13

此逻辑将首先将list中的项目转换为string(str)。有时列表中包含一个元组,例如

alist = [(i12,tiger), 
(113,lion)]

此逻辑将在新行中写入文件每个元组。我们稍后可以eval在读取文件时加载每个元组时使用:

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 

This logic will first convert the items in list to string(str). Sometimes the list contains a tuple like

alist = [(i12,tiger), 
(113,lion)]

This logic will write to file each tuple in a new line. We can later use eval while loading each tuple when reading the file:

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 

回答 14

迭代和添加换行符的另一种方法:

for item in items:
    filewriter.write(f"{item}" + "\n")

Another way of iterating and adding newline:

for item in items:
    filewriter.write(f"{item}" + "\n")

回答 15

在python> 3中,您可以将print*用于参数解包:

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)

In python>3 you can use print and * for argument unpacking:

with open("fout.txt", "w") as fout:
    print(*my_list, sep="\n", file=fout)

回答 16

Python3中,您可以使用此循环

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

In Python3 You Can use this loop

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

回答 17

让avg作为列表,然后:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

您可以根据需要使用%e%s

Let avg be the list, then:

In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')

You can use %e or %s depending on your requirement.


回答 18

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

工作原理:首先,使用内置的打开功能打开文件,并指定文件名称和我们要打开文件的方式。该模式可以是读取模式(’r’),写入模式(’w’)或追加模式(’a’)。我们还可以指定是以文本模式(’t’)还是二进制模式(’b’)阅读,书写或追加内容。实际上,还有更多可用的模式,help(open)将为您提供有关它们的更多详细信息。默认情况下,open()将文件视为“ t”扩展文件,并以“ r’ead”模式将其打开。在我们的示例中,我们首先以写文本模式打开文件,然后使用文件对象的write方法写入文件,然后最终关闭文件。

上面的示例来自Swaroop C H. swaroopch.com 的书“ A Byte of Python”。

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file

How It Works: First, open a file by using the built-in open function and specifying the name of the file and the mode in which we want to open the file. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the file to be a ’t’ext file and opens it in ’r’ead mode. In our example, we first open the file in write text mode and use the write method of the file object to write to the file and then we finally close the file.

The above example is from the book “A Byte of Python” by Swaroop C H. swaroopch.com


如何在Python中使用“ with open”打开多个文件?

问题:如何在Python中使用“ with open”打开多个文件?

我想一次更改几个文件,前提是我可以写入所有文件。我想知道是否可以将多个打开的调用与该with语句组合:

try:
  with open('a', 'w') as a and open('b', 'w') as b:
    do_something()
except IOError as e:
  print 'Operation failed: %s' % e.strerror

如果不可能,那么解决该问题的优雅解决方案会是什么样?

I want to change a couple of files at one time, iff I can write to all of them. I’m wondering if I somehow can combine the multiple open calls with the with statement:

try:
  with open('a', 'w') as a and open('b', 'w') as b:
    do_something()
except IOError as e:
  print 'Operation failed: %s' % e.strerror

If that’s not possible, what would an elegant solution to this problem look like?


回答 0

从Python 2.7(或分别为3.1)开始,您可以编写

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

在Python的早期版本中,有时可以使用 contextlib.nested()嵌套上下文管理器。但是,这对于打开多个文件无法正常工作-有关详细信息,请参见链接的文档。


在极少数情况下,您想一次同时打开可变数量的文件,可以使用contextlib.ExitStack从Python 3.3版开始的:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Do something with "files"

大多数情况下,您拥有一组可变的文件,但是您可能想要一个接一个地打开它们。

As of Python 2.7 (or 3.1 respectively) you can write

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won’t work as expected for opening multiples files, though — see the linked documentation for details.


In the rare case that you want to open a variable number of files all at the same time, you can use contextlib.ExitStack, starting from Python version 3.3:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Do something with "files"

Most of the time you have a variable set of files, you likely want to open them one after the other, though.


回答 1

只需替换and,,您就可以完成:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

Just replace and with , and you’re done:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

回答 2

对于一次打开多个文件或较长的文件路径,将内容分解成多行可能很有用。@Sven Marnach在《Python样式指南》中对另一个答案的评论中建议:

with open('/path/to/InFile.ext', 'r') as file_1, \
     open('/path/to/OutFile.ext', 'w') as file_2:
    file_2.write(file_1.read())

For opening many files at once or for long file paths, it may be useful to break things up over multiple lines. From the Python Style Guide as suggested by @Sven Marnach in comments to another answer:

with open('/path/to/InFile.ext', 'r') as file_1, \
     open('/path/to/OutFile.ext', 'w') as file_2:
    file_2.write(file_1.read())

回答 3

嵌套语句可以完成相同的工作,我认为处理起来更简单。

假设您有inFile.txt,并想同时将其写入两个outFile。

with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)

编辑:

我不了解拒绝投票的原因。我在发布答案之前测试了我的代码,它可以按预期工作:就像问题所要求的那样,它写入所有outFile。无重复写入或写入失败。所以我真的很想知道为什么我的答案被认为是错误的,次优的或类似的东西。

Nested with statements will do the same job, and in my opinion, are more straightforward to deal with.

Let’s say you have inFile.txt, and want to write it into two outFile’s simultaneously.

with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)

EDIT:

I don’t understand the reason of the downvote. I tested my code before publishing my answer, and it works as desired: It writes to all of outFile’s, just as the question asks. No duplicate writing or failing to write. So I am really curious to know why my answer is considered to be wrong, suboptimal or anything like that.


回答 4

因为Python 3.3,你可以使用类ExitStackcontextlib模块到安全地
打开文件的任意数量

它可以管理动态数量的上下文感知对象,这意味着如果您不知道要处理多少文件,它将证明特别有用。

实际上,文档中提到的规范用例正在管理动态数量的文件。

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

如果您对这些细节感兴趣,下面是一个通用示例,以说明ExitStack操作方式:

from contextlib import ExitStack

class X:
    num = 1

    def __init__(self):
        self.num = X.num
        X.num += 1

    def __repr__(self):
        cls = type(self)
        return '{cls.__name__}{self.num}'.format(cls=cls, self=self)

    def __enter__(self):
        print('enter {!r}'.format(self))
        return self.num

    def __exit__(self, exc_type, exc_value, traceback):
        print('exit {!r}'.format(self))
        return True

xs = [X() for _ in range(3)]

with ExitStack() as stack:
    print(len(stack._exit_callbacks)) # number of callbacks called on exit
    nums = [stack.enter_context(x) for x in xs]
    print(len(stack._exit_callbacks))

print(len(stack._exit_callbacks))
print(nums)

输出:

0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]

Since Python 3.3, you can use the class ExitStack from the contextlib module to safely
open an arbitrary number of files.

It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don’t know how many files you are going to handle.

In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

If you are interested in the details, here is a generic example in order to explain how ExitStack operates:

from contextlib import ExitStack

class X:
    num = 1

    def __init__(self):
        self.num = X.num
        X.num += 1

    def __repr__(self):
        cls = type(self)
        return '{cls.__name__}{self.num}'.format(cls=cls, self=self)

    def __enter__(self):
        print('enter {!r}'.format(self))
        return self.num

    def __exit__(self, exc_type, exc_value, traceback):
        print('exit {!r}'.format(self))
        return True

xs = [X() for _ in range(3)]

with ExitStack() as stack:
    print(len(stack._exit_callbacks)) # number of callbacks called on exit
    nums = [stack.enter_context(x) for x in xs]
    print(len(stack._exit_callbacks))

print(len(stack._exit_callbacks))
print(nums)

Output:

0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]

回答 5

使用python 2.6它将无法正常工作,我们必须使用以下方式打开多个文件:

with open('a', 'w') as a:
    with open('b', 'w') as b:

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

回答 6

回答较晚(8年),但对于希望将多个文件合并为一个文件的人,以下功能可能会有所帮助:

def multi_open(_list):
    out=""
    for x in _list:
        try:
            with open(x) as f:
                out+=f.read()
        except:
            pass
            # print(f"Cannot open file {x}")
    return(out)

fl = ["C:/bdlog.txt", "C:/Jts/tws.vmoptions", "C:/not.exist"]
print(multi_open(fl))

2018-10-23 19:18:11.361 PROFILE  [Stop Drivers] [1ms]
2018-10-23 19:18:11.361 PROFILE  [Parental uninit] [0ms]
...
# This file contains VM parameters for Trader Workstation.
# Each parameter should be defined in a separate line and the
...

Late answer (8 yrs), but for someone looking to join multiple files into one, the following function may be of help:

def multi_open(_list):
    out=""
    for x in _list:
        try:
            with open(x) as f:
                out+=f.read()
        except:
            pass
            # print(f"Cannot open file {x}")
    return(out)

fl = ["C:/bdlog.txt", "C:/Jts/tws.vmoptions", "C:/not.exist"]
print(multi_open(fl))

2018-10-23 19:18:11.361 PROFILE  [Stop Drivers] [1ms]
2018-10-23 19:18:11.361 PROFILE  [Parental uninit] [0ms]
...
# This file contains VM parameters for Trader Workstation.
# Each parameter should be defined in a separate line and the
...

如果不存在,Python中的open()不会创建文件

问题:如果不存在,Python中的open()不会创建文件

如果文件以读/写方式打开,或者以不存在的方式创建,然后以读/写方式打开,最好的方法是什么?根据我的阅读,file = open('myfile.dat', 'rw')应该这样做吗?

它对我不起作用(Python 2.6.2),我想知道这是否是版本问题,或者不应该那样工作或做什么。

最重要的是,我只需要解决这个问题。我对其他东西很好奇,但是我所需要的只是做开始部分的好方法。

封闭目录可由用户和组而非其他用户(我在Linux系统上…因此权限775)可写,确切的错误是:

IOError:没有这样的文件或目录。

What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw') should do this, right?

It is not working for me (Python 2.6.2) and I’m wondering if it is a version problem, or not supposed to work like that or what.

The bottom line is, I just need a solution for the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.

The enclosing directory was writeable by user and group, not other (I’m on a Linux system… so permissions 775 in other words), and the exact error was:

IOError: no such file or directory.


回答 0

您应该使用open以下w+模式:

file = open('myfile.dat', 'w+')

You should use open with the w+ mode:

file = open('myfile.dat', 'w+')

回答 1

以下方法的优点是,即使在途中引发了异常,文件也会在块的末尾正确关闭。它等效于try-finally,但要短得多。

with open("file.dat","a+") as f:
    f.write(...)
    ...

a +打开一个文件以进行附加和读取。如果文件存在,则文件指针位于文件的末尾。该文件以追加模式打开。如果该文件不存在,它将创建一个用于读取和写入的新文件。- Python的文件模式

seek()方法设置文件的当前位置。

f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position
  1 .. relative position to current
  2 .. relative position from end

只允许使用“ rwab +”字符;必须完全是“ rwa”之一-请参阅Stack Overflow问题Python文件模式详细信息

The advantage of the following approach is that the file is properly closed at the block’s end, even if an exception is raised on the way. It’s equivalent to try-finally, but much shorter.

with open("file.dat","a+") as f:
    f.write(...)
    ...

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. –Python file modes

seek() method sets the file’s current position.

f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position
  1 .. relative position to current
  2 .. relative position from end

Only “rwab+” characters are allowed; there must be exactly one of “rwa” – see Stack Overflow question Python file modes detail.


回答 2

好的做法是使用以下方法:

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
    f.write('Hello, world!\n')

Good practice is to use the following:

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
    f.write('Hello, world!\n')

回答 3

将“ rw”更改为“ w +”

或使用“ a +”进行附加(不删除现有内容)

Change “rw” to “w+”

Or use ‘a+’ for appending (not erasing existing content)


回答 4

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r +表示读/写

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r+ means read/write


回答 5

从python 3.4开始,您应该使用pathlib“触摸”文件。
与该线程中提出的解决方案相比,这是一种更为优雅的解决方案。

from pathlib import Path

filename = Path('myfile.txt')
filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
file = open(filename)

与目录相同:

filename.mkdir(parents=True, exist_ok=True)

Since python 3.4 you should use pathlib to “touch” files.
It is a much more elegant solution than the proposed ones in this thread.

from pathlib import Path

filename = Path('myfile.txt')
filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
file = open(filename)

Same thing with directories:

filename.mkdir(parents=True, exist_ok=True)

回答 6

我的答案:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

My answer:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

回答 7

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

例:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

我希望这有帮助。[仅供参考,请使用python 3.6.2版]

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

example:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

I hope this helps. [FYI am using python version 3.6.2]


回答 8

open('myfile.dat', 'a') 为我工作,就好。

在py3k中,您的代码将引发ValueError

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

在python-2.6中它引发了IOError

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises ValueError:

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

in python-2.6 it raises IOError.


回答 9

采用:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

注意:打开文件后必须将其关闭,with上下文管理器是让Python为您解决此问题的一种好方法。

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

Note: Files have to be closed after you open them, and the with context manager is a nice way of letting Python take care of this for you.


回答 10

您想对文件做什么?只写它还是读和写?

'w''a'将允许写入,如果文件不存在,则会创建该文件。

如果需要读取文件,则在打开文件之前必须先将其存在。您可以在打开它之前测试它的存在或使用try / except。

What do you want to do with file? Only writing to it or both read and write?

'w', 'a' will allow write and will create the file if it doesn’t exist.

If you need to read from a file, the file has to be exist before open it. You can test its existence before opening it or use a try/except.


回答 11

我认为r+不是rw。我只是一个入门者,这就是我在文档中看到的内容。

I think it’s r+, not rw. I’m just a starter, and that’s what I’ve seen in the documentation.


回答 12

使用w +写入文件,如果存在则截断,使用r +读取文件,如果文件不存在则创建一个,但不写入(并返回null),或者使用a +创建新文件或追加到现有文件。

Put w+ for writing the file, truncating if it exist, r+ to read the file, creating one if it don’t exist but not writing (and returning null) or a+ for creating a new file or appending to a existing one.


回答 13

因此,您想将数据写入文件,但前提是该文件尚不存在?

通过使用鲜为人知的x模式open()而不是通常的w模式,可以轻松解决此问题。例如:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

如果文件是二进制模式,请使用模式xb而不是xt。

So You want to write data to a file, but only if it doesn’t already exist?.

This problem is easily solved by using the little-known x mode to open() instead of the usual w mode. For example:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

If the file is binary mode, use mode xb instead of xt.


回答 14

如果您想打开它进行读写,那么我假设您不想在打开文件时截断它,并且希望在打开文件后立即读取文件。所以这是我正在使用的解决方案:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

If you want to open it to read and write, I’m assuming you don’t want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I’m using:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

回答 15

也许这会有所帮助

首先将os模块导入py文件

import os

然后创建一个名为save_file的变量并将其设置为您要制作html或txt的文件,在这种情况下,将其设置为txt文件

save_file = "history.txt"

然后定义一个函数,该函数将使用os.path.is file方法检查文件是否存在,如果不存在,它将创建一个文件

def check_into():
if os.path.isfile(save_file):
    print("history file exists..... \nusing for writting....")
else:
    print("history file not exists..... \ncreating it..... ")
    file = open(save_file, 'w')
    time.sleep(2)
    print('file created ')
    file.close()

最后调用函数

check_into()

may be this will help

first import os module into your py file

import os

then create a variable named save_file and set it to file you want to make html or txt in this case a txt file

save_file = "history.txt"

then define a function that will use os.path.is file method to check if file exist and if not it will create a file

def check_into():
if os.path.isfile(save_file):
    print("history file exists..... \nusing for writting....")
else:
    print("history file not exists..... \ncreating it..... ")
    file = open(save_file, 'w')
    time.sleep(2)
    print('file created ')
    file.close()

and at last call the function

check_into()

回答 16

import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)
import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)

将字符串打印到文本文件

问题:将字符串打印到文本文件

我正在使用Python打开文本文档:

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

我想将字符串变量的值替换TotalAmount为文本文档。有人可以让我知道怎么做吗?

I’m using Python to open a text document:

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

I want to substitute the value of a string variable TotalAmount into the text document. Can someone please let me know how to do this?


回答 0

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

如果使用上下文管理器,则将自动为您关闭文件

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

如果您使用的是Python2.6或更高版本,则最好使用 str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

对于python2.7及更高版本,您可以使用{}代替{0}

在Python3中,fileprint函数有一个可选参数

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6引入了f字符串作为另一种选择

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you use a context manager, the file is closed automatically for you

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

If you’re using Python2.6 or higher, it’s preferred to use str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}

In Python3, there is an optional file parameter to the print function

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 introduced f-strings for another alternative

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

回答 1

如果要传递多个参数,可以使用元组

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

更多:在python中打印多个参数

In case you want to pass multiple arguments you can use a tuple

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

More: Print multiple arguments in python


回答 2

如果您使用的是Python3。

然后可以使用打印功能

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

对于python2

这是Python打印字符串到文本文件的示例

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

If you are using Python3.

then you can use Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

For python2

this is the example of Python Print String To Text File

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

回答 3

如果您使用的是numpy,则只需一行即可将单个(或乘)字符串打印到文件中:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')

If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')

回答 4

使用pathlib模块时,不需要缩进。

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

从python 3.6开始,f字符串可用。

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")

With using pathlib module, indentation isn’t needed.

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

As of python 3.6, f-strings is available.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")

如何删除文件或文件夹?

问题:如何删除文件或文件夹?

如何在Python中删除文件或文件夹?

How to delete a file or folder in Python?


回答 0


PathPython 3.4+ pathlib模块中的对象还公开了这些实例方法:


Path objects from the Python 3.4+ pathlib module also expose these instance methods:


回答 1

Python语法删除文件

import os
os.remove("/tmp/<file_name>.txt")

要么

import os
os.unlink("/tmp/<file_name>.txt")

要么

适用于Python版本> 3.5的pathlib

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok = False)

Unlink方法用于删除文件或符号链接。

如果missing_ok为false(默认值),则在路径不存在时引发FileNotFoundError。
如果missing_ok为true,则将忽略FileNotFoundError异常(与POSIX rm -f命令相同的行为)。
在版本3.8中更改:添加了missing_ok参数。

最佳实践

  1. 首先,检查文件或文件夹是否存在,然后仅删除该文件。这可以通过两种方式实现:
    一。os.path.isfile("/path/to/file")
    b。采用exception handling.

实例os.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

异常处理

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

预期输出

输入要删除的文件名:demo.txt
错误:demo.txt-没有这样的文件或目录。

输入要删除的文件名:rrr.txt
错误:rrr.txt-不允许操作。

输入要删除的文件名:foo.txt

删除文件夹的Python语法

shutil.rmtree()

范例 shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version > 3.5

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

Unlink method used to remove the file or the symbolik link.

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

Best practice

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. Use exception handling.

EXAMPLE for os.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

Exception Handling

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

RESPECTIVE OUTPUT

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

Python syntax to delete a folder

shutil.rmtree()

Example for shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

回答 2

采用

shutil.rmtree(path[, ignore_errors[, onerror]])

(请参阅关于shutil的完整文档)和/或

os.remove

os.rmdir

(关于os的完整文档。)

Use

shutil.rmtree(path[, ignore_errors[, onerror]])

(See complete documentation on shutil) and/or

os.remove

and

os.rmdir

(Complete documentation on os.)


回答 3

这是同时使用os.remove和的强大功能shutil.rmtree

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path) or os.path.islink(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))

Here is a robust function that uses both os.remove and shutil.rmtree:

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path) or os.path.islink(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))

回答 4

您可以使用内置的pathlib模块(需要Python 3.4+,但也有旧版本PyPI上的反向移植:pathlibpathlib2)。

要删除文件,可以使用以下unlink方法:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

rmdir删除文件夹的方法:

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()

You can use the built-in pathlib module (requires Python 3.4+, but there are backports for older versions on PyPI: pathlib, pathlib2).

To remove a file there is the unlink method:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

Or the rmdir method to remove an empty folder:

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()

回答 5

如何在Python中删除文件或文件夹?

对于Python 3,要分别删除文件和目录,请分别使用unlink和对象方法:rmdir Path

from pathlib import Path
dir_path = Path.home() / 'directory' 
file_path = dir_path / 'file'

file_path.unlink() # remove file

dir_path.rmdir()   # remove directory

请注意,您还可以将相对路径与Path对象一起使用,并且可以使用来检查当前的工作目录Path.cwd

要在Python 2中删除单个文件和目录,请参见下面标记的部分。

要删除包含目录的目录,请使用shutil.rmtree,请注意,该目录在Python 2和3中可用:

from shutil import rmtree

rmtree(dir_path)

示范

Path对象是Python 3.4中的新增功能。

让我们用一个目录和文件来演示用法。请注意,我们使用/来连接路径的各个部分,这解决了操作系统之间的问题以及Windows上使用反斜杠(在其中您需要将反斜杠加倍,\\或者使用原始字符串,如r"foo\bar")引起的问题:

from pathlib import Path

# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()

file_path = directory_path / 'file'
file_path.touch()

现在:

>>> file_path.is_file()
True

现在让我们删除它们。首先文件:

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False

我们可以使用通配符删除多个文件-首先,我们为此创建一些文件:

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()

然后只需遍历全局模式:

>>> for each_file_path in directory_path.glob('*.my'):
...     print(f'removing {each_file_path}')
...     each_file_path.unlink()
... 
removing ~/directory/foo.my
removing ~/directory/bar.my

现在,演示删除目录:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

如果我们要删除目录及其中的所有内容怎么办?对于此用例,请使用shutil.rmtree

让我们重新创建目录和文件:

file_path.parent.mkdir()
file_path.touch()

并注意rmdir除非它为空,否则它将失败,这就是rmtree如此方便的原因:

>>> directory_path.rmdir()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
    self._accessor.rmdir(self)
  File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
    return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'

现在,导入rmtree并将目录传递给该功能:

from shutil import rmtree
rmtree(directory_path)      # remove everything 

我们可以看到整个内容已被删除:

>>> directory_path.exists()
False

Python 2

如果您使用的是Python 2,则有一个名为pathlib2的pathlib模块的反向端口,可以使用pip进行安装:

$ pip install pathlib2

然后您可以将库别名为 pathlib

import pathlib2 as pathlib

或者直接导入Path对象(如此处所示):

from pathlib2 import Path

如果太多,您可以使用删除文件os.removeos.unlink

from os import unlink, remove
from os.path import join, expanduser

remove(join(expanduser('~'), 'directory/file'))

要么

unlink(join(expanduser('~'), 'directory/file'))

您可以使用以下命令删除目录os.rmdir

from os import rmdir

rmdir(join(expanduser('~'), 'directory'))

请注意,还有一个os.removedirs-它仅以递归方式删除空目录,但它可能适合您的用例。

How do I delete a file or folder in Python?

For Python 3, to remove the file and directory individually, use the unlink and rmdir Path object methods respectively:

from pathlib import Path
dir_path = Path.home() / 'directory' 
file_path = dir_path / 'file'

file_path.unlink() # remove file

dir_path.rmdir()   # remove directory

Note that you can also use relative paths with Path objects, and you can check your current working directory with Path.cwd.

For removing individual files and directories in Python 2, see the section so labeled below.

To remove a directory with contents, use shutil.rmtree, and note that this is available in Python 2 and 3:

from shutil import rmtree

rmtree(dir_path)

Demonstration

New in Python 3.4 is the Path object.

Let’s use one to create a directory and file to demonstrate usage. Note that we use the / to join the parts of the path, this works around issues between operating systems and issues from using backslashes on Windows (where you’d need to either double up your backslashes like \\ or use raw strings, like r"foo\bar"):

from pathlib import Path

# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()

file_path = directory_path / 'file'
file_path.touch()

and now:

>>> file_path.is_file()
True

Now let’s delete them. First the file:

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False

We can use globbing to remove multiple files – first let’s create a few files for this:

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()

Then just iterate over the glob pattern:

>>> for each_file_path in directory_path.glob('*.my'):
...     print(f'removing {each_file_path}')
...     each_file_path.unlink()
... 
removing ~/directory/foo.my
removing ~/directory/bar.my

Now, demonstrating removing the directory:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

What if we want to remove a directory and everything in it? For this use-case, use shutil.rmtree

Let’s recreate our directory and file:

file_path.parent.mkdir()
file_path.touch()

and note that rmdir fails unless it’s empty, which is why rmtree is so convenient:

>>> directory_path.rmdir()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
    self._accessor.rmdir(self)
  File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
    return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'

Now, import rmtree and pass the directory to the funtion:

from shutil import rmtree
rmtree(directory_path)      # remove everything 

and we can see the whole thing has been removed:

>>> directory_path.exists()
False

Python 2

If you’re on Python 2, there’s a backport of the pathlib module called pathlib2, which can be installed with pip:

$ pip install pathlib2

And then you can alias the library to pathlib

import pathlib2 as pathlib

Or just directly import the Path object (as demonstrated here):

from pathlib2 import Path

If that’s too much, you can remove files with os.remove or os.unlink

from os import unlink, remove
from os.path import join, expanduser

remove(join(expanduser('~'), 'directory/file'))

or

unlink(join(expanduser('~'), 'directory/file'))

and you can remove directories with os.rmdir:

from os import rmdir

rmdir(join(expanduser('~'), 'directory'))

Note that there is also a os.removedirs – it only removes empty directories recursively, but it may suit your use-case.


回答 6

import os

folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)

for f in fileList:
    filePath = folder + '/'+f

    if os.path.isfile(filePath):
        os.remove(filePath)

    elif os.path.isdir(filePath):
        newFileList = os.listdir(filePath)
        for f1 in newFileList:
            insideFilePath = filePath + '/' + f1

            if os.path.isfile(insideFilePath):
                os.remove(insideFilePath)
import os

folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)

for f in fileList:
    filePath = folder + '/'+f

    if os.path.isfile(filePath):
        os.remove(filePath)

    elif os.path.isdir(filePath):
        newFileList = os.listdir(filePath)
        for f1 in newFileList:
            insideFilePath = filePath + '/' + f1

            if os.path.isfile(insideFilePath):
                os.remove(insideFilePath)

回答 7

shutil.rmtree是异步函数,因此,如果要检查它是否完成,可以使用while … loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

shutil.rmtree is the asynchronous function, so if you want to check when it complete, you can use while…loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

回答 8

删除文件:

os.unlink(path, *, dir_fd=None)

要么

os.remove(path, *, dir_fd=None)

这两个功能在语义上是相同的。此功能删除(删除)文件路径。如果path不是文件,而是目录,则会引发异常。

删除文件夹:

shutil.rmtree(path, ignore_errors=False, onerror=None)

要么

os.rmdir(path, *, dir_fd=None)

为了删除整个目录树,shutil.rmtree()可以使用。os.rmdir仅在目录为空且存在时才起作用。

要递归删除父文件夹:

os.removedirs(name)

它用self删除每个空的父目录,直到有一些内容的父目录为止

例如 os.removedirs(’abc / xyz / pqr’)如果目录为空,则会按顺序abc / xyz / pqr,abc / xyz和abc删除目录。

欲了解更多信息检查官方文档:os.unlinkos.removeos.rmdirshutil.rmtreeos.removedirs

For deleting files:

os.unlink(path, *, dir_fd=None)

or

os.remove(path, *, dir_fd=None)

Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.

For deleting folders:

shutil.rmtree(path, ignore_errors=False, onerror=None)

or

os.rmdir(path, *, dir_fd=None)

In order to remove whole directory trees, shutil.rmtree() can be used. os.rmdir only works when the directory is empty and exists.

For deleting folders recursively towards parent:

os.removedirs(name)

It remove every empty parent directory with self until parent which has some content

ex. os.removedirs(‘abc/xyz/pqr’) will remove the directories by order ‘abc/xyz/pqr’, ‘abc/xyz’ and ‘abc’ if they are empty.

For more info check official doc: os.unlink , os.remove, os.rmdir , shutil.rmtree, os.removedirs


回答 9

删除文件夹中的所有文件

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)

删除目录中的所有文件夹

from shutil import rmtree
import os

// os.path.join()  # current working directory.

for dirct in os.listdir(os.path.join('path/to/folder')):
    rmtree(os.path.join('path/to/folder',dirct))

To remove all files in folder

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)

To remove all folders in a directory

from shutil import rmtree
import os

// os.path.join()  # current working directory.

for dirct in os.listdir(os.path.join('path/to/folder')):
    rmtree(os.path.join('path/to/folder',dirct))

回答 10

为了避免ÉricAraujo 的注释突出显示的TOCTOU问题,您可以捕获异常以调用正确的方法:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

因为shutil.rmtree()将仅删除目录,os.remove()或者os.unlink()仅将删除文件。

To avoid the TOCTOU issue highlighted by Éric Araujo’s comment, you can catch an exception to call the correct method:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

Since shutil.rmtree() will only remove directories and os.remove() or os.unlink() will only remove files.


回答 11

subprocess如果您喜欢编写漂亮且易读的代码,那么我建议您使用:

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

而且,如果您不是软件工程师,那么可以考虑使用Jupyter。您可以简单地输入bash命令:

!rm -r my_dir

传统上,您使用shutil

import shutil
shutil.rmtree(my_dir) 

I recommend using subprocess if writing a beautiful and readable code is your cup of tea:

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

And if you are not a software engineer, then maybe consider using Jupyter; you can simply type bash commands:

!rm -r my_dir

Traditionally, you use shutil:

import shutil
shutil.rmtree(my_dir) 

将行写入文件的正确方法?

问题:将行写入文件的正确方法?

我已经习惯了 print >>f, "hi there"

但是,似乎print >>已经弃用了。推荐使用哪种方法进行上述操作?

更新:关于…的所有这些答案,"\n"这是通用的还是特定于Unix的?IE,我应该"\r\n"在Windows上运行吗?

I’m used to doing print >>f, "hi there"

However, it seems that print >> is getting deprecated. What is the recommended way to do the line above?

Update: Regarding all those answers with "\n"…is this universal or Unix-specific? IE, should I be doing "\r\n" on Windows?


回答 0

这应该很简单:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

从文档:

os.linesep写入以文本模式打开的文件时(默认),请勿用作行终止符;在所有平台上都使用一个’\ n’代替。

一些有用的读物​​:

This should be as simple as:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single ‘\n’ instead, on all platforms.

Some useful reading:


回答 1

您应该使用print()Python 2.6+以上版本提供的功能

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

对于Python 3,您不需要import,因为该 print()功能是默认设置。

替代方法是使用:

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

引用Python文档中有关换行符的内容:

在输出中,如果换行符为None,则所有'\n'写入的字符都会转换为系统默认的行分隔符os.linesep。如果newline是'',则不会进行翻译。如果换行符是其他任何合法值,'\n'则将写入的所有字符转换为给定的字符串。

You should use the print() function which is available since Python 2.6+

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

For Python 3 you don’t need the import, since the print() function is the default.

The alternative would be to use:

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

Quoting from Python documentation regarding newlines:

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.


回答 2

Python文档建议是这样的:

with open('file_to_write', 'w') as f:
    f.write('file contents\n')

所以这就是我通常的方式:)

来自docs.python.org的声明:

在处理文件对象时,最好使用‘with’关键字。这样做的好处是,即使在执行过程中引发了异常,文件在其套件完成后也将正确关闭。它也比编写等效的try-finally块短得多。

The python docs recommend this way:

with open('file_to_write', 'w') as f:
    f.write('file contents\n')

So this is the way I usually do it :)

Statement from docs.python.org:

It is good practice to use the ‘with’ keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.


回答 3

关于os.linesep:

这是Windows上未经编辑的Python 2.7.1解释器的确切会话:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.linesep
'\r\n'
>>> f = open('myfile','w')
>>> f.write('hi there\n')
>>> f.write('hi there' + os.linesep) # same result as previous line ?????????
>>> f.close()
>>> open('myfile', 'rb').read()
'hi there\r\nhi there\r\r\n'
>>>

在Windows上:

正如预期的那样,os.linesep确实产生相同的结果一样'\n'。它不可能产生相同的结果。'hi there' + os.linesep等同于'hi there\r\n'等同于'hi there\n'

就是这么简单:使用\n它将自动转换为os.linesep。自从将Python首次移植到Windows以来,事情就变得如此简单。

在非Windows系统上使用os.linesep是没有意义的,并且在Windows上会产生错误的结果。

请勿使用os.linesep!

Regarding os.linesep:

Here is an exact unedited Python 2.7.1 interpreter session on Windows:

Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.linesep
'\r\n'
>>> f = open('myfile','w')
>>> f.write('hi there\n')
>>> f.write('hi there' + os.linesep) # same result as previous line ?????????
>>> f.close()
>>> open('myfile', 'rb').read()
'hi there\r\nhi there\r\r\n'
>>>

On Windows:

As expected, os.linesep does NOT produce the same outcome as '\n'. There is no way that it could produce the same outcome. 'hi there' + os.linesep is equivalent to 'hi there\r\n', which is NOT equivalent to 'hi there\n'.

It’s this simple: use \n which will be translated automatically to os.linesep. And it’s been that simple ever since the first port of Python to Windows.

There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows.

DO NOT USE os.linesep!


回答 4

我认为没有“正确”的方法。

我会用:

with open ('myfile', 'a') as f: f.write ('hi there\n')

在纪念蒂姆·托迪(Tim Toady)中

I do not think there is a “correct” way.

I would use:

with open ('myfile', 'a') as f: f.write ('hi there\n')

In memoriam Tim Toady.


回答 5

在Python 3中,它是一个函数,但是在Python 2中,您可以将其添加到源文件的顶部:

from __future__ import print_function

那你做

print("hi there", file=f)

In Python 3 it is a function, but in Python 2 you can add this to the top of the source file:

from __future__ import print_function

Then you do

print("hi there", file=f)

回答 6

如果您要写入大量数据,并且速度是一个问题,那么您可能应该考虑一下f.write(...)。我进行了快速的速度比较,它比print(..., file=f)执行大量写操作时要快得多。

import time    

start = start = time.time()
with open("test.txt", 'w') as f:
    for i in range(10000000):
        # print('This is a speed test', file=f)
        # f.write('This is a speed test\n')
end = time.time()
print(end - start)

write我的机器上,平均完成print时间为2.45秒,而耗时则为(9.76s)的4倍。话虽这么说,在大多数现实情况下这都不是问题。

如果您选择使用,print(..., file=f)您可能会发现您可能会不希望取消换行符,或将其替换为其他内容。这可以通过设置可选end参数来完成,例如;

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)

我建议您使用哪种选择,with因为它使代码更易于阅读。

更新:这种性能差异是由以下事实解释的:write高度缓冲并在实际对磁盘进行任何写操作之前返回(请参阅此答案),而print(可能)使用行缓冲。一个简单的测试就是检查长写的性能,因为行缓冲的缺点(在速度方面)不太明显。

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")

现在,性能差异变得不那么明显了,的平均时间为2.20s write和3.10s print。如果您需要连接一串字符串来获得这种良好的性能,那么性能会受到影响,因此使用案例中print效率更高的情况很少见。

If you are writing a lot of data and speed is a concern you should probably go with f.write(...). I did a quick speed comparison and it was considerably faster than print(..., file=f) when performing a large number of writes.

import time    

start = start = time.time()
with open("test.txt", 'w') as f:
    for i in range(10000000):
        # print('This is a speed test', file=f)
        # f.write('This is a speed test\n')
end = time.time()
print(end - start)

On average write finished in 2.45s on my machine, whereas print took about 4 times as long (9.76s). That being said, in most real-world scenarios this will not be an issue.

If you choose to go with print(..., file=f) you will probably find that you’ll want to suppress the newline from time to time, or replace it with something else. This can be done by setting the optional end parameter, e.g.;

with open("test", 'w') as f:
    print('Foo1,', file=f, end='')
    print('Foo2,', file=f, end='')
    print('Foo3', file=f)

Whichever way you choose I’d suggest using with since it makes the code much easier to read.

Update: This difference in performance is explained by the fact that write is highly buffered and returns before any writes to disk actually take place (see this answer), whereas print (probably) uses line buffering. A simple test for this would be to check performance for long writes as well, where the disadvantages (in terms of speed) for line buffering would be less pronounced.

start = start = time.time()
long_line = 'This is a speed test' * 100
with open("test.txt", 'w') as f:
    for i in range(1000000):
        # print(long_line, file=f)
        # f.write(long_line + '\n')
end = time.time()

print(end - start, "s")

The performance difference now becomes much less pronounced, with an average time of 2.20s for write and 3.10s for print. If you need to concatenate a bunch of strings to get this loooong line performance will suffer, so use-cases where print would be more efficient are a bit rare.


回答 7

从3.5开始,您还可以使用pathlib

Path.write_text(data, encoding=None, errors=None)

打开以文本模式指向的文件,向其中写入数据,然后关闭文件:

import pathlib

pathlib.Path('textfile.txt').write_text('content')

Since 3.5 you can also use the pathlib for that purpose:

Path.write_text(data, encoding=None, errors=None)

Open the file pointed to in text mode, write data to it, and close the file:

import pathlib

pathlib.Path('textfile.txt').write_text('content')

回答 8

当您说Line时,它表示一些序列化的字符,它们以’\ n’字符结尾。行应该在最后一点,所以我们应该在每行的末尾考虑’\ n’。这是解决方案:

with open('YOURFILE.txt', 'a') as the_file:
    the_file.write("Hello")

在追加模式下,每次写入光标后移至新行,如果要使用w模式,则应\nwrite()函数末尾添加字符:

the_file.write("Hello\n")

When you said Line it means some serialized characters which are ended to ‘\n’ characters. Line should be last at some point so we should consider ‘\n’ at the end of each line. Here is solution:

with open('YOURFILE.txt', 'a') as the_file:
    the_file.write("Hello")

in append mode after each write the cursor move to new line, if you want to use w mode you should add \n characters at the end of the write() function:

the_file.write("Hello\n")

回答 9

也可以按以下方式使用该io模块:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

One can also use the io module as in:

import io
my_string = "hi there"

with io.open("output_file.txt", mode='w', encoding='utf-8') as f:
    f.write(my_string)

回答 10

可以使用烧瓶中的文件写入文本:

filehandle = open("text.txt", "w")
filebuffer = ["hi","welcome","yes yes welcome"]
filehandle.writelines(filebuffer)
filehandle.close()

To write text in a file in the flask can be used:

filehandle = open("text.txt", "w")
filebuffer = ["hi","welcome","yes yes welcome"]
filehandle.writelines(filebuffer)
filehandle.close()

回答 11

您也可以尝试 filewriter

pip install filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]

写入 my_file.txt

接受可迭代对象或带有__str__支持的对象。

You can also try filewriter

pip install filewriter

from filewriter import Writer

Writer(filename='my_file', ext='txt') << ["row 1 hi there", "row 2"]

Writes into my_file.txt

Takes an iterable or an object with __str__ support.


回答 12

当我需要写很多新行时,我定义一个使用print函数的lambda :

out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')

这种方法的好处是可以利用该功能可用的所有print功能。

更新:正如Georgy在评论部分中提到的那样,可以通过以下partial功能进一步改善此想法:

from functools import partial
fwl = partial(print, file=out)

恕我直言,这是一种功能更强,含糊不清的方法。

When I need to write new lines a lot, I define a lambda that uses a print function:

out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')

This approach has the benefit that it can utilize all the features that are available with the print function.

Update: As is mentioned by Georgy in the comment section, it is possible to improve this idea further with the partial function:

from functools import partial
fwl = partial(print, file=out)

IMHO, this is a more functional and less cryptic approach.


在Python中以扩展名.txt查找目录中的所有文件

问题:在Python中以扩展名.txt查找目录中的所有文件

如何.txt在python中具有扩展名的目录中找到所有文件?

How can I find all the files in a directory having the extension .txt in python?


回答 0

您可以使用glob

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

或简单地os.listdir

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

或者如果要遍历目录,请使用os.walk

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

You can use glob:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

or simply os.listdir:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

or if you want to traverse directory, use os.walk:

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))

回答 1

使用glob

>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']

Use glob.

>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']

回答 2

这样的事情应该做的

for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print file

Something like that should do the job

for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print file

回答 3

这样的事情会起作用:

>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']

Something like this will work:

>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']

回答 4

您可以简单地使用pathlibs 1glob

import pathlib

list(pathlib.Path('your_directory').glob('*.txt'))

或循环:

for txt_file in pathlib.Path('your_directory').glob('*.txt'):
    # do something with "txt_file"

如果您希望递归可以使用 .glob('**/*.txt)


1pathlib模块包含在python 3.4的标准库中。但是,即使在较旧的Python版本(例如,使用condapip)上,您也可以安装该模块的后端口:pathlibpathlib2

You can simply use pathlibs glob 1:

import pathlib

list(pathlib.Path('your_directory').glob('*.txt'))

or in a loop:

for txt_file in pathlib.Path('your_directory').glob('*.txt'):
    # do something with "txt_file"

If you want it recursive you can use .glob('**/*.txt)


1The pathlib module was included in the standard library in python 3.4. But you can install back-ports of that module even on older Python versions (i.e. using conda or pip): pathlib and pathlib2.


回答 5

import os

path = 'mypath/path' 
files = os.listdir(path)

files_txt = [i for i in files if i.endswith('.txt')]
import os

path = 'mypath/path' 
files = os.listdir(path)

files_txt = [i for i in files if i.endswith('.txt')]

回答 6

我喜欢os.walk()

import os

for root, dirs, files in os.walk(dir):
    for f in files:
        if os.path.splitext(f)[1] == '.txt':
            fullpath = os.path.join(root, f)
            print(fullpath)

或使用生成器:

import os

fileiter = (os.path.join(root, f)
    for root, _, files in os.walk(dir)
    for f in files)
txtfileiter = (f for f in fileiter if os.path.splitext(f)[1] == '.txt')
for txt in txtfileiter:
    print(txt)

I like os.walk():

import os

for root, dirs, files in os.walk(dir):
    for f in files:
        if os.path.splitext(f)[1] == '.txt':
            fullpath = os.path.join(root, f)
            print(fullpath)

Or with generators:

import os

fileiter = (os.path.join(root, f)
    for root, _, files in os.walk(dir)
    for f in files)
txtfileiter = (f for f in fileiter if os.path.splitext(f)[1] == '.txt')
for txt in txtfileiter:
    print(txt)

回答 7

以下是相同版本的更多版本,它们会产生稍微不同的结果:

glob.iglob()

import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories 
    print f

glob.glob1()

print glob.glob1("/mydir", "*.tx?")  # literal_directory, basename_pattern

fnmatch.filter()

import fnmatch, os
print fnmatch.filter(os.listdir("/mydir"), "*.tx?") # include dot-files

Here’s more versions of the same that produce slightly different results:

glob.iglob()

import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories 
    print f

glob.glob1()

print glob.glob1("/mydir", "*.tx?")  # literal_directory, basename_pattern

fnmatch.filter()

import fnmatch, os
print fnmatch.filter(os.listdir("/mydir"), "*.tx?") # include dot-files

回答 8

path.py是另一种替代方法:https : //github.com/jaraco/path.py

from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
    print f

path.py is another alternative: https://github.com/jaraco/path.py

from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
    print f

回答 9

Python v3.5 +

在递归函数中使用os.scandir的快速方法。在文件夹和子文件夹中搜索具有指定扩展名的所有文件。

import os

def findFilesInFolder(path, pathList, extension, subFolders = True):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:        Base directory to find files
    pathList:    A list that stores all paths
    extension:   File extension to find
    subFolders:  Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    """

    try:   # Trapping a OSError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and entry.path.endswith(extension):
                pathList.append(entry.path)
            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                pathList = findFilesInFolder(entry.path, pathList, extension, subFolders)
    except OSError:
        print('Cannot access ' + path +'. Probably a permissions error')

    return pathList

dir_name = r'J:\myDirectory'
extension = ".txt"

pathList = []
pathList = findFilesInFolder(dir_name, pathList, extension, True)

2019年4月更新

如果要搜索包含10,000s个文件的目录,则附加到列表的效率将降低。“屈服”结果是一个更好的解决方案。我还提供了一个将输出转换为Pandas Dataframe的功能。

import os
import re
import pandas as pd
import numpy as np


def findFilesInFolderYield(path,  extension, containsTxt='', subFolders = True, excludeText = ''):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    if type(containsTxt) == str: # if a string and not in a list
        containsTxt = [containsTxt]

    myregexobj = re.compile('\.' + extension + '$')    # Makes sure the file extension is at the end and is preceded by a .

    try:   # Trapping a OSError or FileNotFoundError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and myregexobj.search(entry.path): # 

                bools = [True for txt in containsTxt if txt in entry.path and (excludeText == '' or excludeText not in entry.path)]

                if len(bools)== len(containsTxt):
                    yield entry.stat().st_size, entry.stat().st_atime_ns, entry.stat().st_mtime_ns, entry.stat().st_ctime_ns, entry.path

            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                yield from findFilesInFolderYield(entry.path,  extension, containsTxt, subFolders)
    except OSError as ose:
        print('Cannot access ' + path +'. Probably a permissions error ', ose)
    except FileNotFoundError as fnf:
        print(path +' not found ', fnf)

def findFilesInFolderYieldandGetDf(path,  extension, containsTxt, subFolders = True, excludeText = ''):
    """  Converts returned data from findFilesInFolderYield and creates and Pandas Dataframe.
    Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """

    fileSizes, accessTimes, modificationTimes, creationTimes , paths  = zip(*findFilesInFolderYield(path,  extension, containsTxt, subFolders))
    df = pd.DataFrame({
            'FLS_File_Size':fileSizes,
            'FLS_File_Access_Date':accessTimes,
            'FLS_File_Modification_Date':np.array(modificationTimes).astype('timedelta64[ns]'),
            'FLS_File_Creation_Date':creationTimes,
            'FLS_File_PathName':paths,
                  })

    df['FLS_File_Modification_Date'] = pd.to_datetime(df['FLS_File_Modification_Date'],infer_datetime_format=True)
    df['FLS_File_Creation_Date'] = pd.to_datetime(df['FLS_File_Creation_Date'],infer_datetime_format=True)
    df['FLS_File_Access_Date'] = pd.to_datetime(df['FLS_File_Access_Date'],infer_datetime_format=True)

    return df

ext =   'txt'  # regular expression 
containsTxt=[]
path = 'C:\myFolder'
df = findFilesInFolderYieldandGetDf(path,  ext, containsTxt, subFolders = True)

Python v3.5+

Fast method using os.scandir in a recursive function. Searches for all files with a specified extension in folder and sub-folders.

import os

def findFilesInFolder(path, pathList, extension, subFolders = True):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:        Base directory to find files
    pathList:    A list that stores all paths
    extension:   File extension to find
    subFolders:  Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    """

    try:   # Trapping a OSError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and entry.path.endswith(extension):
                pathList.append(entry.path)
            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                pathList = findFilesInFolder(entry.path, pathList, extension, subFolders)
    except OSError:
        print('Cannot access ' + path +'. Probably a permissions error')

    return pathList

dir_name = r'J:\myDirectory'
extension = ".txt"

pathList = []
pathList = findFilesInFolder(dir_name, pathList, extension, True)

Update April 2019

If you are searching over directories which contain 10,000s files, appending to a list becomes inefficient. ‘Yielding’ the results is a better solution. I have also included a function to convert the output to a Pandas Dataframe.

import os
import re
import pandas as pd
import numpy as np


def findFilesInFolderYield(path,  extension, containsTxt='', subFolders = True, excludeText = ''):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    if type(containsTxt) == str: # if a string and not in a list
        containsTxt = [containsTxt]

    myregexobj = re.compile('\.' + extension + '$')    # Makes sure the file extension is at the end and is preceded by a .

    try:   # Trapping a OSError or FileNotFoundError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and myregexobj.search(entry.path): # 

                bools = [True for txt in containsTxt if txt in entry.path and (excludeText == '' or excludeText not in entry.path)]

                if len(bools)== len(containsTxt):
                    yield entry.stat().st_size, entry.stat().st_atime_ns, entry.stat().st_mtime_ns, entry.stat().st_ctime_ns, entry.path

            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                yield from findFilesInFolderYield(entry.path,  extension, containsTxt, subFolders)
    except OSError as ose:
        print('Cannot access ' + path +'. Probably a permissions error ', ose)
    except FileNotFoundError as fnf:
        print(path +' not found ', fnf)

def findFilesInFolderYieldandGetDf(path,  extension, containsTxt, subFolders = True, excludeText = ''):
    """  Converts returned data from findFilesInFolderYield and creates and Pandas Dataframe.
    Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """

    fileSizes, accessTimes, modificationTimes, creationTimes , paths  = zip(*findFilesInFolderYield(path,  extension, containsTxt, subFolders))
    df = pd.DataFrame({
            'FLS_File_Size':fileSizes,
            'FLS_File_Access_Date':accessTimes,
            'FLS_File_Modification_Date':np.array(modificationTimes).astype('timedelta64[ns]'),
            'FLS_File_Creation_Date':creationTimes,
            'FLS_File_PathName':paths,
                  })

    df['FLS_File_Modification_Date'] = pd.to_datetime(df['FLS_File_Modification_Date'],infer_datetime_format=True)
    df['FLS_File_Creation_Date'] = pd.to_datetime(df['FLS_File_Creation_Date'],infer_datetime_format=True)
    df['FLS_File_Access_Date'] = pd.to_datetime(df['FLS_File_Access_Date'],infer_datetime_format=True)

    return df

ext =   'txt'  # regular expression 
containsTxt=[]
path = 'C:\myFolder'
df = findFilesInFolderYieldandGetDf(path,  ext, containsTxt, subFolders = True)

回答 10

Python具有执行此操作的所有工具:

import os

the_dir = 'the_dir_that_want_to_search_in'
all_txt_files = filter(lambda x: x.endswith('.txt'), os.listdir(the_dir))

Python has all tools to do this:

import os

the_dir = 'the_dir_that_want_to_search_in'
all_txt_files = filter(lambda x: x.endswith('.txt'), os.listdir(the_dir))

回答 11

要以Python方式将“ dataPath”文件夹中的所有“ .txt”文件名作为列表获取:

from os import listdir
from os.path import isfile, join
path = "/dataPath/"
onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".txt")]
print onlyTxtFiles

To get all ‘.txt’ file names inside ‘dataPath’ folder as a list in a Pythonic way:

from os import listdir
from os.path import isfile, join
path = "/dataPath/"
onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".txt")]
print onlyTxtFiles

回答 12

试试这个,这将递归找到所有文件:

import glob, os
os.chdir("H:\\wallpaper")# use whatever directory you want

#double\\ no single \

for file in glob.glob("**/*.txt", recursive = True):
    print(file)

Try this this will find all your files recursively:

import glob, os
os.chdir("H:\\wallpaper")# use whatever directory you want

#double\\ no single \

for file in glob.glob("**/*.txt", recursive = True):
    print(file)

回答 13

import os
import sys 

if len(sys.argv)==2:
    print('no params')
    sys.exit(1)

dir = sys.argv[1]
mask= sys.argv[2]

files = os.listdir(dir); 

res = filter(lambda x: x.endswith(mask), files); 

print res
import os
import sys 

if len(sys.argv)==2:
    print('no params')
    sys.exit(1)

dir = sys.argv[1]
mask= sys.argv[2]

files = os.listdir(dir); 

res = filter(lambda x: x.endswith(mask), files); 

print res

回答 14

我做了一个测试(Python 3.6.4,W7x64),看哪个解决方案对于一个文件夹(没有子目录)最快,以获得具有特定扩展名的文件的完整文件路径列表。

要长话短说,这个任务os.listdir()是最快的是1.7倍的速度作为下一个最好的:os.walk()(!休息后),2.7倍一样快pathlib,3.2倍的速度比os.scandir()和3.3倍的速度比glob
请记住,当您需要递归结果时,这些结果将改变。如果您复制/粘贴以下一种方法,请添加.lower(),否则在搜索.ext时找不到.EXT。

import os
import pathlib
import timeit
import glob

def a():
    path = pathlib.Path().cwd()
    list_sqlite_files = [str(f) for f in path.glob("*.sqlite")]

def b(): 
    path = os.getcwd()
    list_sqlite_files = [f.path for f in os.scandir(path) if os.path.splitext(f)[1] == ".sqlite"]

def c():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(".sqlite")]

def d():
    path = os.getcwd()
    os.chdir(path)
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob("*.sqlite")]

def e():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob1(str(path), "*.sqlite")]

def f():
    path = os.getcwd()
    list_sqlite_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".sqlite"):
                list_sqlite_files.append( os.path.join(root, file) )
        break



print(timeit.timeit(a, number=1000))
print(timeit.timeit(b, number=1000))
print(timeit.timeit(c, number=1000))
print(timeit.timeit(d, number=1000))
print(timeit.timeit(e, number=1000))
print(timeit.timeit(f, number=1000))

结果:

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274

I did a test (Python 3.6.4, W7x64) to see which solution is the fastest for one folder, no subdirectories, to get a list of complete file paths for files with a specific extension.

To make it short, for this task os.listdir() is the fastest and is 1.7x as fast as the next best: os.walk() (with a break!), 2.7x as fast as pathlib, 3.2x faster than os.scandir() and 3.3x faster than glob.
Please keep in mind, that those results will change when you need recursive results. If you copy/paste one method below, please add a .lower() otherwise .EXT would not be found when searching for .ext.

import os
import pathlib
import timeit
import glob

def a():
    path = pathlib.Path().cwd()
    list_sqlite_files = [str(f) for f in path.glob("*.sqlite")]

def b(): 
    path = os.getcwd()
    list_sqlite_files = [f.path for f in os.scandir(path) if os.path.splitext(f)[1] == ".sqlite"]

def c():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(".sqlite")]

def d():
    path = os.getcwd()
    os.chdir(path)
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob("*.sqlite")]

def e():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob1(str(path), "*.sqlite")]

def f():
    path = os.getcwd()
    list_sqlite_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".sqlite"):
                list_sqlite_files.append( os.path.join(root, file) )
        break



print(timeit.timeit(a, number=1000))
print(timeit.timeit(b, number=1000))
print(timeit.timeit(c, number=1000))
print(timeit.timeit(d, number=1000))
print(timeit.timeit(e, number=1000))
print(timeit.timeit(f, number=1000))

Results:

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274

回答 15

此代码使我的生活更简单。

import os
fnames = ([file for root, dirs, files in os.walk(dir)
    for file in files
    if file.endswith('.txt') #or file.endswith('.png') or file.endswith('.pdf')
    ])
for fname in fnames: print(fname)

This code makes my life simpler.

import os
fnames = ([file for root, dirs, files in os.walk(dir)
    for file in files
    if file.endswith('.txt') #or file.endswith('.png') or file.endswith('.pdf')
    ])
for fname in fnames: print(fname)

回答 16

使用fnmatch:https : //docs.python.org/2/library/fnmatch.html

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

Use fnmatch: https://docs.python.org/2/library/fnmatch.html

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

回答 17

为了从同一目录中名为“ data”的文件夹中获取“ .txt”文件名的数组,我通常使用以下简单代码行:

import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]

To get an array of “.txt” file names from a folder called “data” in the same directory I usually use this simple line of code:

import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]

回答 18

我建议您使用fnmatch和upper方法。这样,您可以找到以下任意一项:

  1. 名称。txt ;
  2. 名称。TXT ;
  3. 名称。文本文件

import fnmatch
import os

    for file in os.listdir("/Users/Johnny/Desktop/MyTXTfolder"):
        if fnmatch.fnmatch(file.upper(), '*.TXT'):
            print(file)

I suggest you to use fnmatch and the upper method. In this way you can find any of the following:

  1. Name.txt;
  2. Name.TXT;
  3. Name.Txt

.

import fnmatch
import os

    for file in os.listdir("/Users/Johnny/Desktop/MyTXTfolder"):
        if fnmatch.fnmatch(file.upper(), '*.TXT'):
            print(file)

回答 19

这是一个 extend()

types = ('*.jpg', '*.png')
images_list = []
for files in types:
    images_list.extend(glob.glob(os.path.join(path, files)))

Here’s one with extend()

types = ('*.jpg', '*.png')
images_list = []
for files in types:
    images_list.extend(glob.glob(os.path.join(path, files)))

回答 20

带有子目录的功能解决方案:

from fnmatch import filter
from functools import partial
from itertools import chain
from os import path, walk

print(*chain(*(map(partial(path.join, root), filter(filenames, "*.txt")) for root, _, filenames in walk("mydir"))))

Functional solution with sub-directories:

from fnmatch import filter
from functools import partial
from itertools import chain
from os import path, walk

print(*chain(*(map(partial(path.join, root), filter(filenames, "*.txt")) for root, _, filenames in walk("mydir"))))

回答 21

如果文件夹包含很多文件或内存是一个限制,请考虑使用生成器:

def yield_files_with_extensions(folder_path, file_extension):
   for _, _, files in os.walk(folder_path):
       for file in files:
           if file.endswith(file_extension):
               yield file

选项A:重复

for f in yield_files_with_extensions('.', '.txt'): 
    print(f)

选项B:全部获取

files = [f for f in yield_files_with_extensions('.', '.txt')]

In case the folder contains a lot of files or memory is an constraint, consider using generators:

def yield_files_with_extensions(folder_path, file_extension):
   for _, _, files in os.walk(folder_path):
       for file in files:
           if file.endswith(file_extension):
               yield file

Option A: Iterate

for f in yield_files_with_extensions('.', '.txt'): 
    print(f)

Option B: Get all

files = [f for f in yield_files_with_extensions('.', '.txt')]

回答 22

可复制的解决方案,类似于ghostdog之一:

def get_all_filepaths(root_path, ext):
    """
    Search all files which have a given extension within root_path.

    This ignores the case of the extension and searches subdirectories, too.

    Parameters
    ----------
    root_path : str
    ext : str

    Returns
    -------
    list of str

    Examples
    --------
    >>> get_all_filepaths('/run', '.lock')
    ['/run/unattended-upgrades.lock',
     '/run/mlocate.daily.lock',
     '/run/xtables.lock',
     '/run/mysqld/mysqld.sock.lock',
     '/run/postgresql/.s.PGSQL.5432.lock',
     '/run/network/.ifstate.lock',
     '/run/lock/asound.state.lock']
    """
    import os
    all_files = []
    for root, dirs, files in os.walk(root_path):
        for filename in files:
            if filename.lower().endswith(ext):
                all_files.append(os.path.join(root, filename))
    return all_files

A copy-pastable solution similar to the one of ghostdog:

def get_all_filepaths(root_path, ext):
    """
    Search all files which have a given extension within root_path.

    This ignores the case of the extension and searches subdirectories, too.

    Parameters
    ----------
    root_path : str
    ext : str

    Returns
    -------
    list of str

    Examples
    --------
    >>> get_all_filepaths('/run', '.lock')
    ['/run/unattended-upgrades.lock',
     '/run/mlocate.daily.lock',
     '/run/xtables.lock',
     '/run/mysqld/mysqld.sock.lock',
     '/run/postgresql/.s.PGSQL.5432.lock',
     '/run/network/.ifstate.lock',
     '/run/lock/asound.state.lock']
    """
    import os
    all_files = []
    for root, dirs, files in os.walk(root_path):
        for filename in files:
            if filename.lower().endswith(ext):
                all_files.append(os.path.join(root, filename))
    return all_files

回答 23

使用Python OS模块查找具有特定扩展名的文件。

简单的例子在这里:

import os

# This is the path where you want to search
path = r'd:'  

# this is extension you want to detect
extension = '.txt'   # this can be : .jpg  .png  .xls  .log .....

for root, dirs_list, files_list in os.walk(path):
    for file_name in files_list:
        if os.path.splitext(file_name)[-1] == extension:
            file_name_path = os.path.join(root, file_name)
            print file_name
            print file_name_path   # This is the full path of the filter file

use Python OS module to find files with specific extension.

the simple example is here :

import os

# This is the path where you want to search
path = r'd:'  

# this is extension you want to detect
extension = '.txt'   # this can be : .jpg  .png  .xls  .log .....

for root, dirs_list, files_list in os.walk(path):
    for file_name in files_list:
        if os.path.splitext(file_name)[-1] == extension:
            file_name_path = os.path.join(root, file_name)
            print file_name
            print file_name_path   # This is the full path of the filter file

回答 24

许多用户回答了os.walk答案,其中包括所有文件,还包括所有目录和子目录及其文件。

import os


def files_in_dir(path, extension=''):
    """
       Generator: yields all of the files in <path> ending with
       <extension>

       \param   path       Absolute or relative path to inspect,
       \param   extension  [optional] Only yield files matching this,

       \yield              [filenames]
    """


    for _, dirs, files in os.walk(path):
        dirs[:] = []  # do not recurse directories.
        yield from [f for f in files if f.endswith(extension)]

# Example: print all the .py files in './python'
for filename in files_in_dir('./python', '*.py'):
    print("-", filename)

或者在不需要生成器的情况下停下来:

path, ext = "./python", ext = ".py"
for _, _, dirfiles in os.walk(path):
    matches = (f for f in dirfiles if f.endswith(ext))
    break

for filename in matches:
    print("-", filename)

如果要将匹配用于其他内容,则可能要使其成为列表而不是生成器表达式:

    matches = [f for f in dirfiles if f.endswith(ext)]

Many users have replied with os.walk answers, which includes all files but also all directories and subdirectories and their files.

import os


def files_in_dir(path, extension=''):
    """
       Generator: yields all of the files in <path> ending with
       <extension>

       \param   path       Absolute or relative path to inspect,
       \param   extension  [optional] Only yield files matching this,

       \yield              [filenames]
    """


    for _, dirs, files in os.walk(path):
        dirs[:] = []  # do not recurse directories.
        yield from [f for f in files if f.endswith(extension)]

# Example: print all the .py files in './python'
for filename in files_in_dir('./python', '*.py'):
    print("-", filename)

Or for a one off where you don’t need a generator:

path, ext = "./python", ext = ".py"
for _, _, dirfiles in os.walk(path):
    matches = (f for f in dirfiles if f.endswith(ext))
    break

for filename in matches:
    print("-", filename)

If you are going to use matches for something else, you may want to make it a list rather than a generator expression:

    matches = [f for f in dirfiles if f.endswith(ext)]

回答 25

使用forloop的简单方法:

import os

dir = ["e","x","e"]

p = os.listdir('E:')  #path

for n in range(len(p)):
   name = p[n]
   myfile = [name[-3],name[-2],name[-1]]  #for .txt
   if myfile == dir :
      print(name)
   else:
      print("nops")

虽然这可以使它更加笼统。

A simple method by using for loop :

import os

dir = ["e","x","e"]

p = os.listdir('E:')  #path

for n in range(len(p)):
   name = p[n]
   myfile = [name[-3],name[-2],name[-1]]  #for .txt
   if myfile == dir :
      print(name)
   else:
      print("nops")

Though this can be made more generalised .