Hướng dẫn python tempfile csv - python tempfile csv

So I'm writing a test for this class [edited to be more clear]:

Nội dung chính

  • Deprecated functions and variables¶
  • How do I create a temp file in Python?
  • Can you create a new CSV file in Python?
  • How do I create a tmp file?
  • What is used to store temporary data in Python?

class SpreadSheet[object]:
    '''awesome docstring'''
    def __init__[self, filename]:
        self.filename = filename
        self.table = []
        self.headers = []

        with open[self.filename] as csvfile:
            filereader = reader[csvfile, delimiter=',']
            for row in filereader:
                self.table.append[row]

    def create_headers[self, populations]:
        ...code...

    def lookup_header[self, ltr]:
        ...code...

    def write_header[self, targetfile]:
        ...code...

that so far looks like this:

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...

And I get this error:

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found

I've scoured many other topics like this that point to the use of tempfile to make a named object or something that can actually be called using with open.... And while I did actually get that to work, my issues was when I tried to use the csv package to format my self.table for me into a csv formatted raw "string" [like the raw input of a csv file in other words].

Any pointers on how I can test this differently or make the current code work? Again I'm trying to:

  1. figure out how to use csv to do all the formatting heavy-lifting to load up a fake csv file from my self.table so that I don't have to make a huge string formatting expression

  2. make sure that the fake file works with

    class TestSpreadSheet[unittest.TestCase]:
        @contextmanager
        def make_fake_csv[self, data]:
            self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
            with open[self.fake_namefile, 'w'] as fake_csv:
                fake_writer = csv.writer[fake_csv]
                fake_writer.writerows[data]
            yield self.fake_namefile.name
            os.unlink[self.fake_namefile.name]
    
        def setUp[self]:
            self.headers = []
            self.table = [
                ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]
    
        def test___init__[self]:
            with self.make_fake_csv[self.table] as temp_csv:
                spread_sheet = SpreadSheet[temp_csv]
                self.assertEqual[
                    self.table, spread_sheet.table]
    
        ...tests for other functions...
    
    1 as used in my original class
    class TestSpreadSheet[unittest.TestCase]:
        @contextmanager
        def make_fake_csv[self, data]:
            self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
            with open[self.fake_namefile, 'w'] as fake_csv:
                fake_writer = csv.writer[fake_csv]
                fake_writer.writerows[data]
            yield self.fake_namefile.name
            os.unlink[self.fake_namefile.name]
    
        def setUp[self]:
            self.headers = []
            self.table = [
                ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]
    
        def test___init__[self]:
            with self.make_fake_csv[self.table] as temp_csv:
                spread_sheet = SpreadSheet[temp_csv]
                self.assertEqual[
                    self.table, spread_sheet.table]
    
        ...tests for other functions...
    
    2 when the test is run

  3. can be used further to run the test of the other functions because they too need to instantiate

    class TestSpreadSheet[unittest.TestCase]:
        @contextmanager
        def make_fake_csv[self, data]:
            self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
            with open[self.fake_namefile, 'w'] as fake_csv:
                fake_writer = csv.writer[fake_csv]
                fake_writer.writerows[data]
            yield self.fake_namefile.name
            os.unlink[self.fake_namefile.name]
    
        def setUp[self]:
            self.headers = []
            self.table = [
                ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]
    
        def test___init__[self]:
            with self.make_fake_csv[self.table] as temp_csv:
                spread_sheet = SpreadSheet[temp_csv]
                self.assertEqual[
                    self.table, spread_sheet.table]
    
        ...tests for other functions...
    
    2 with a file in order to perform their functions.

And as a side question, is it "leaner" to make a fake "memory" file to do things like this [this is what I'm attempting above] or is is just simpler to make an actual temporary file on the disk and load it up during testing and use a

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
4 function to delete it?

Source code: Lib/tempfile.py

This module creates temporary files and directories. It works on all supported platforms.

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
5,
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
6,
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
7, and
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
8 are high-level interfaces which provide automatic cleanup and can be used as context managers.
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9 and
in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
0 are lower-level functions which require manual cleanup.

All the user-callable functions and constructors take additional arguments which allow direct control over the location and name of temporary files and directories. Files names used by this module include a string of random characters which allows those files to be securely created in shared temporary directories. To maintain backward compatibility, the argument order is somewhat odd; it is recommended to use keyword arguments for clarity.

The module defines the following user-callable items:

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
1
in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
2[mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None]

Return a file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9. It will be destroyed as soon as it is closed [including an implicit close when the object is garbage collected]. Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

The resulting object can be used as a context manager [see Examples]. On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.

The mode parameter defaults to

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
4 so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is stored. buffering, encoding, errors and newline are interpreted as for
in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
5.

The dir, prefix and suffix parameters have the same meaning and defaults as with

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9.

The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
7 attribute is the underlying true file object.

The

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
8 flag is used if it is available and works [Linux-specific, requires Linux kernel 3.11 or later].

On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias for NamedTemporaryFile.

Raises an auditing event

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
9 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.

Changed in version 3.5: The

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
8 flag is now used if available.

Changed in version 3.8: Added errors parameter.

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
1
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
3[mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None]

This function operates exactly as

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
4 does, except that the file is guaranteed to have a visible name in the file system [on Unix, the directory entry is not unlinked]. That name can be retrieved from the
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
5 attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms [it can be so used on Unix; it cannot on Windows]. If delete is true [the default], the file is deleted as soon as it is closed. The returned object is always a file-like object whose
in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
7 attribute is the underlying true file object. This file-like object can be used in a
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
7 statement, just like a normal file.

Tăng một sự kiện kiểm toán

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
9 với đối số
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.auditing event
in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
9 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.

Đã thay đổi trong phiên bản 3.8: Đã thêm tham số lỗi.Added errors parameter.

Lớp ________ 21 ________ 41 [max_size = 0, mode = 'w+b', buffering =- 1, mã hóa = none, newline = none[max_size=0, mode='w+b', buffering=- 1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None]

Lớp này hoạt động chính xác như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
4, ngoại trừ dữ liệu được trình bày trong bộ nhớ cho đến khi kích thước tệp vượt quá MAX_SIZE hoặc cho đến khi phương thức tệp ____ ____43 được gọi, tại thời điểm đó, nội dung được ghi vào đĩa và hoạt động tiến hành như với
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
4.

Tệp kết quả có một phương thức bổ sung,

>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
5, khiến cho tệp cuộn qua một tệp trên đĩa bất kể kích thước của nó.

Đối tượng được trả về là một đối tượng giống như tệp có thuộc tính

>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
6 là đối tượng
>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
7 hoặc
>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
8 [tùy thuộc vào chế độ nhị phân hay văn bản được chỉ định] hoặc đối tượng tệp thực, tùy thuộc vào việc
>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
5 đã được gọi. Đối tượng giống như tệp này có thể được sử dụng trong câu lệnh
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
7, giống như một tệp thông thường.

Đã thay đổi trong phiên bản 3.3: Phương thức cắt ngắn hiện chấp nhận đối số tempfile1.the truncate method now accepts a tempfile1 argument.

Đã thay đổi trong phiên bản 3.8: Đã thêm tham số lỗi.Added errors parameter.

Lớp ________ 21 ________ 41 [max_size = 0, mode = 'w+b', buffering =- 1, mã hóa = none, newline = none[suffix=None, prefix=None, dir=None, ignore_cleanup_errors=False]

Lớp này hoạt động chính xác như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
4, ngoại trừ dữ liệu được trình bày trong bộ nhớ cho đến khi kích thước tệp vượt quá MAX_SIZE hoặc cho đến khi phương thức tệp ____ ____43 được gọi, tại thời điểm đó, nội dung được ghi vào đĩa và hoạt động tiến hành như với
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
4.Examples]. On completion of the context or destruction of the temporary directory object, the newly created temporary directory and all its contents are removed from the filesystem.

Tệp kết quả có một phương thức bổ sung,

>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
5, khiến cho tệp cuộn qua một tệp trên đĩa bất kể kích thước của nó.

Đối tượng được trả về là một đối tượng giống như tệp có thuộc tính

>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
6 là đối tượng
>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
7 hoặc
>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
8 [tùy thuộc vào chế độ nhị phân hay văn bản được chỉ định] hoặc đối tượng tệp thực, tùy thuộc vào việc
>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False
5 đã được gọi. Đối tượng giống như tệp này có thể được sử dụng trong câu lệnh
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
7, giống như một tệp thông thường.

Đã thay đổi trong phiên bản 3.3: Phương thức cắt ngắn hiện chấp nhận đối số tempfile1.auditing event with open...2 with argument

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.

Lớp ________ 21 ________ 53 [hậu tố = không, tiền tố = none, dir = none, ond_cleanup_errors = false

Lớp này tạo ra một thư mục tạm thời bằng cách sử dụng các quy tắc tương tự như

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
0. Đối tượng kết quả có thể được sử dụng làm trình quản lý ngữ cảnh [xem ví dụ]. Khi hoàn thành bối cảnh hoặc phá hủy đối tượng thư mục tạm thời, thư mục tạm thời mới được tạo và tất cả các nội dung của nó được xóa khỏi hệ thống tập tin.Added ignore_cleanup_errors parameter.

Tên thư mục có thể được lấy từ thuộc tính
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
5 của đối tượng được trả về. Khi đối tượng được trả về được sử dụng làm Trình quản lý ngữ cảnh,
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
5 sẽ được gán cho mục tiêu của mệnh đề tempfile7 trong câu lệnh
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
7, nếu có.[suffix=None, prefix=None, dir=None, text=False]

Thư mục có thể được làm sạch rõ ràng bằng cách gọi phương thức tempfile9. Nếu bỏ qua_cleanup_errors là đúng, bất kỳ ngoại lệ chưa được xử lý nào trong quá trình dọn dẹp rõ ràng hoặc ẩn [chẳng hạn như with open...0 xóa các tệp mở trên Windows] sẽ bị bỏ qua và các mục có thể tháo rời còn lại bị xóa trên cơ sở hiệu ứng tốt nhất. Mặt khác, các lỗi sẽ được nêu ra trong bất kỳ việc dọn dẹp ngữ cảnh nào [cuộc gọi tempfile9, thoát khỏi trình quản lý ngữ cảnh, khi đối tượng được thu thập rác hoặc trong khi tắt máy phiên dịch].

Tăng một sự kiện kiểm toán with open...2 với đối số

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.

Mới trong phiên bản 3.2.

Đã thay đổi trong phiên bản 3.10: Đã thêm tham số bỏ qua_cleanup_errors.

________ 21 ________ 65 [hậu tố = không, tiền tố = none, dir = none, text = false] ¶

Tạo một tập tin tạm thời theo cách an toàn nhất có thể. Không có điều kiện đua trong việc tạo tệp, giả sử rằng nền tảng thực hiện đúng cờ with open...6 cho with open...7. Tệp có thể đọc được và chỉ có thể ghi bằng ID người dùng tạo. Nếu nền tảng sử dụng các bit quyền để cho biết liệu một tệp có thể thực thi được hay không, thì tệp không thể thực thi được bởi không ai. Bộ mô tả tập tin không được kế thừa bởi các quá trình con.

Không giống như

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
4, người dùng
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9 chịu trách nhiệm xóa tệp tạm thời khi thực hiện với nó.

Nếu hậu tố không phải là csv0, tên tệp sẽ kết thúc với hậu tố đó, nếu không sẽ không có hậu tố.

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9 không đặt dấu chấm giữa tên tệp và hậu tố; Nếu bạn cần một, hãy đặt nó ở đầu hậu tố.

Tăng một sự kiện kiểm toán

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
9 với đối số
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.auditing event
in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
9 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.

Nếu tiền tố không phải là csv0, tên tệp sẽ bắt đầu với tiền tố đó; Nếu không, một tiền tố mặc định được sử dụng. Mặc định là giá trị trả về của csv3 hoặc csv4, nếu phù hợp.suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to csv0 to cause an appropriate default value to be used.

Đã thay đổi trong phiên bản 3.6: Tham số Dir hiện chấp nhận một đối tượng giống như đường dẫn.The dir parameter now accepts a path-like object.

________ 21 ________ 85 [hậu tố = không, tiền tố = none, dir = none] ¶[suffix=None, prefix=None, dir=None]

Tạo một thư mục tạm thời theo cách an toàn nhất có thể. Không có điều kiện chủng tộc trong việc tạo thư mục. Thư mục có thể đọc được, có thể ghi và chỉ có thể tìm kiếm bằng ID người dùng tạo.

Người dùng của

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
0 chịu trách nhiệm xóa thư mục tạm thời và nội dung của nó khi thực hiện với nó.

Tiền tố, hậu tố và đối số DIR giống như đối với

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9.

in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
0 Trả về tên đường dẫn tuyệt đối của thư mục mới.

Tăng một sự kiện kiểm toán with open...2 với đối số

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.auditing event with open...2 with argument
>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
0.

Đã thay đổi trong phiên bản 3.5: Hậu tố, tiền tố và dir hiện có thể được cung cấp theo byte để có được giá trị trả về byte. Trước đó, chỉ có STR được phép. Hậu tố và tiền tố hiện chấp nhận và mặc định là csv0 để gây ra giá trị mặc định phù hợp được sử dụng.suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to csv0 to cause an appropriate default value to be used.

Đã thay đổi trong phiên bản 3.6: Tham số Dir hiện chấp nhận một đối tượng giống như đường dẫn.The dir parameter now accepts a path-like object.

________ 21 ________ 93 [][]

Trả về tên của thư mục được sử dụng cho các tệp tạm thời. Điều này xác định giá trị mặc định cho đối số DIR cho tất cả các hàm trong mô -đun này.

Python tìm kiếm một danh sách tiêu chuẩn các thư mục để tìm một danh sách mà người dùng gọi có thể tạo tệp. Danh sách là:

  1. Thư mục được đặt tên bởi biến môi trường csv4.csv4 environment variable.

  2. Thư mục được đặt tên bởi biến môi trường csv5.csv5 environment variable.

  3. Thư mục được đặt tên bởi biến môi trường csv6.csv6 environment variable.

  4. Vị trí cụ thể của nền tảng:

    • Trên Windows, các thư mục csv7, csv8, csv9 và

      class TestSpreadSheet[unittest.TestCase]:
          @contextmanager
          def make_fake_csv[self, data]:
              self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
              with open[self.fake_namefile, 'w'] as fake_csv:
                  fake_writer = csv.writer[fake_csv]
                  fake_writer.writerows[data]
              yield self.fake_namefile.name
              os.unlink[self.fake_namefile.name]
      
          def setUp[self]:
              self.headers = []
              self.table = [
                  ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]
      
          def test___init__[self]:
              with self.make_fake_csv[self.table] as temp_csv:
                  spread_sheet = SpreadSheet[temp_csv]
                  self.assertEqual[
                      self.table, spread_sheet.table]
      
          ...tests for other functions...
      
      00, theo thứ tự đó.

    • Trên tất cả các nền tảng khác, các thư mục

      class TestSpreadSheet[unittest.TestCase]:
          @contextmanager
          def make_fake_csv[self, data]:
              self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
              with open[self.fake_namefile, 'w'] as fake_csv:
                  fake_writer = csv.writer[fake_csv]
                  fake_writer.writerows[data]
              yield self.fake_namefile.name
              os.unlink[self.fake_namefile.name]
      
          def setUp[self]:
              self.headers = []
              self.table = [
                  ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]
      
          def test___init__[self]:
              with self.make_fake_csv[self.table] as temp_csv:
                  spread_sheet = SpreadSheet[temp_csv]
                  self.assertEqual[
                      self.table, spread_sheet.table]
      
          ...tests for other functions...
      
      01,
      class TestSpreadSheet[unittest.TestCase]:
          @contextmanager
          def make_fake_csv[self, data]:
              self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
              with open[self.fake_namefile, 'w'] as fake_csv:
                  fake_writer = csv.writer[fake_csv]
                  fake_writer.writerows[data]
              yield self.fake_namefile.name
              os.unlink[self.fake_namefile.name]
      
          def setUp[self]:
              self.headers = []
              self.table = [
                  ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]
      
          def test___init__[self]:
              with self.make_fake_csv[self.table] as temp_csv:
                  spread_sheet = SpreadSheet[temp_csv]
                  self.assertEqual[
                      self.table, spread_sheet.table]
      
          ...tests for other functions...
      
      02 và
      class TestSpreadSheet[unittest.TestCase]:
          @contextmanager
          def make_fake_csv[self, data]:
              self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
              with open[self.fake_namefile, 'w'] as fake_csv:
                  fake_writer = csv.writer[fake_csv]
                  fake_writer.writerows[data]
              yield self.fake_namefile.name
              os.unlink[self.fake_namefile.name]
      
          def setUp[self]:
              self.headers = []
              self.table = [
                  ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
                  ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]
      
          def test___init__[self]:
              with self.make_fake_csv[self.table] as temp_csv:
                  spread_sheet = SpreadSheet[temp_csv]
                  self.assertEqual[
                      self.table, spread_sheet.table]
      
          ...tests for other functions...
      
      03, theo thứ tự đó.

  5. Là một phương sách cuối cùng, thư mục làm việc hiện tại.

Kết quả của tìm kiếm này được lưu trữ, xem mô tả của

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
04 bên dưới.

Đã thay đổi trong phiên bản 3.10: Luôn trả về STR. Trước đây, nó sẽ trả về bất kỳ giá trị

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
04 nào bất kể loại nào miễn là nó không phải là csv0.Always returns a str. Previously it would return any
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
04 value regardless of type so long as it was not csv0.

________ 21 ________ 108 [][]

Giống như

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
09 nhưng giá trị trả về là trong byte.

Mới trong phiên bản 3.5.

________ 21 ________ 111 ​​[][]

Trả về tiền tố tệp được sử dụng để tạo các tệp tạm thời. Điều này không chứa thành phần thư mục.

________ 21 ________ 113 [][]

Giống như csv3 nhưng giá trị trả về là trong byte.

Mới trong phiên bản 3.5.

________ 21 ________ 111 ​​[]

Trả về tiền tố tệp được sử dụng để tạo các tệp tạm thời. Điều này không chứa thành phần thư mục.

________ 21 ________ 113 []path-like object.

Giống như csv3 nhưng giá trị trả về là trong byte.

Mô -đun sử dụng biến toàn cầu để lưu trữ tên của thư mục được sử dụng cho các tệp tạm thời được trả về bởi

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
09. Nó có thể được đặt trực tiếp để ghi đè quá trình lựa chọn, nhưng điều này không được khuyến khích. Tất cả các chức năng trong mô -đun này có một đối số DIR có thể được sử dụng để chỉ định thư mục. Đây là cách tiếp cận được đề xuất không gây ngạc nhiên cho mã không nghi ngờ khác bằng cách thay đổi hành vi API toàn cầu.

________ 21 ________ 117¶

Khi được đặt thành một giá trị khác với csv0, biến này xác định giá trị mặc định cho đối số DIR cho các hàm được xác định trong mô -đun này, bao gồm loại, byte hoặc str. Nó không thể là một đối tượng giống như đường dẫn.

Nếu

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
04 là csv0 [mặc định] tại bất kỳ cuộc gọi nào đến bất kỳ chức năng nào ở trên ngoại trừ csv3, nó sẽ được khởi tạo theo thuật toán được mô tả trong
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
09.

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
...     fp.write[b'Hello world!']
...     fp.seek[0]
...     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
...     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed

Ghi chú

Hãy coi chừng nếu bạn đặt

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
04 thành giá trị byte, thì có một tác dụng phụ khó chịu: Loại trả lại mặc định toàn cầu là
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9 và
in make_fake_csv
with open[self.fake_namefile, 'w'] as fake_csv:
TypeError: coercing to Unicode: need string or buffer, instance found
0 thay đổi thành byte khi không có đối số
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
26,
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
27 hoặc
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
28 của STR được cung cấp. Vui lòng không viết mã mong đợi hoặc tùy thuộc vào điều này. Hành vi khó xử này được duy trì để tương thích với việc thực hiện lịch sử.

Ví dụ;[suffix='', prefix='tmp', dir=None]

Dưới đây là một số ví dụ về cách sử dụng điển hình của mô -đun

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
29:Use
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9 instead.

Chức năng và biến không dùng nữa

Một cách lịch sử để tạo các tệp tạm thời là trước tiên tạo tên tệp với hàm

class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
30 và sau đó tạo một tệp bằng tên này. Thật không may, điều này không an toàn, bởi vì một quy trình khác có thể tạo một tệp có tên này trong thời gian giữa cuộc gọi đến
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
30 và nỗ lực tiếp theo để tạo tệp theo quy trình đầu tiên. Giải pháp là kết hợp hai bước và tạo tệp ngay lập tức. Cách tiếp cận này được sử dụng bởi
class TestSpreadSheet[unittest.TestCase]:
    @contextmanager
    def make_fake_csv[self, data]:
        self.fake_namefile = tempfile.NamedTemporaryFile[delete=False]
        with open[self.fake_namefile, 'w'] as fake_csv:
            fake_writer = csv.writer[fake_csv]
            fake_writer.writerows[data]
        yield self.fake_namefile.name
        os.unlink[self.fake_namefile.name]

    def setUp[self]:
        self.headers = []
        self.table = [
            ['Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6', 'Col7', 'Col8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8'],
            ['val1', 'val2', 'val3', 'val4', 'val5', 'val6', 'val7', 'val8']]

    def test___init__[self]:
        with self.make_fake_csv[self.table] as temp_csv:
            spread_sheet = SpreadSheet[temp_csv]
            self.assertEqual[
                self.table, spread_sheet.table]

    ...tests for other functions...
9 và các chức năng khác được mô tả ở trên.

________ 21 ________ 134 [hậu tố = '', tiền tố = 'tmp', dir = none] ¶

>>> f = NamedTemporaryFile[delete=False]
>>> f.name
'/tmp/tmptjujjt'
>>> f.write[b"Hello World!\n"]
13
>>> f.close[]
>>> os.unlink[f.name]
>>> os.path.exists[f.name]
False

Làm cách nào để tạo một tệp tạm thời trong Python?

Tạo các tập tin tạm thời..

Đầu tiên, chúng ta phải nhập tempfile sau đó tệp được tạo bằng hàm tạm thờifile [] ..

Tệp được mở trong chế độ W+B [cả đọc và ghi vào tệp mở] theo mặc định ..

Hàm này tạo một tệp tạm thời trong thư mục tạm thời và trả về một đối tượng tệp ..

Bạn có thể tạo một tệp CSV mới trong Python không?

Các bước để viết tệp CSV trước, hãy mở tệp CSV để ghi [chế độ W] bằng cách sử dụng hàm Open []. Thứ hai, tạo đối tượng người viết CSV bằng cách gọi hàm writer [] của mô -đun CSV. Thứ ba, ghi dữ liệu vào tệp CSV bằng cách gọi phương thức Writerow [] hoặc Writerows [] của đối tượng Writer CSV.open the CSV file for writing [ w mode] by using the open[] function. Second, create a CSV writer object by calling the writer[] function of the csv module. Third, write data to CSV file by calling the writerow[] or writerows[] method of the CSV writer object.

Làm cách nào để tạo tệp TMP?

Để chèn một tên tệp tạm thời mới:..

Trong một hành động ghi vào tệp trong một bước, nhấp chuột phải vào trường tệp ..

Nhấp vào Tên tệp> Tên tệp mới. Cửa sổ thuộc tính FileName Mở ..

Xác định các thuộc tính cho tệp tạm thời: Tên: Cung cấp tên cho tệp tạm thời [ví dụ: báo cáo]. ....

Bấm OK ..

Những gì được sử dụng để lưu trữ dữ liệu tạm thời trong Python?

Python cung cấp một mô -đun được gọi là tempfile, giúp việc tạo và xử lý các tệp tạm thời dễ dàng hơn. Mô -đun này cung cấp một vài phương pháp để tạo các tệp và thư mục tạm thời theo những cách khác nhau. Tempfile có ích bất cứ khi nào bạn muốn sử dụng các tệp tạm thời để lưu trữ dữ liệu trong chương trình Python.tempfile, which makes creating and handling temporary files easier. This module provides a few methods to create temporary files and directories in different ways. tempfile comes in handy whenever you want to use temporary files to store data in a Python program.

Bài Viết Liên Quan

Chủ Đề