简体   繁体   English

了解在 Python 中连接文件的代码?

[英]Understanding code for concatenating files in Python?

I need to concatenate a few large files in Python, and came across a helpful snippet of code here, but am having trouble understanding a small part of it.我需要在 Python 中连接几个大文件,并在这里遇到了一个有用的代码片段,但我无法理解其中的一小部分。 Here is the code:这是代码:

filenames = ['file1.txt', 'file2.txt', ...]
     with open('path/to/output/file', 'w') as outfile:
          for fname in filenames:
               with open(fname) as infile:
                    for line in infile:
                         outfile.write(line)

The only thing I don't understand is what the 'w' is supposed to represent, so it would be great if someone explained it.我唯一不明白的是'w'应该代表什么,所以如果有人解释它会很棒。 Thanks!谢谢!

When you open a file, you must specify a mode in which it will be opened.打开文件时,必须指定打开文件的模式。 The character 'w' stands for 'write', and it means that the file will be opened for writing, after it has been truncated.字符'w'代表 'write',它意味着文件将在被截断后打开以进行写入。

Subsequent calls to open() in your code snippet ( with open(fname) as infile ) need not explicitly define a mode, since 'r' (which stands for 'read') is the default mode used when calling open() .在代码片段中对open()后续调用( with open(fname) as infile )不需要明确定义模式,因为'r' (代表 'read')是调用open()时使用的默认模式。 They are equivalent to writing:它们相当于写:

with open(fname, 'r') as infile:
    # rest of code here

See the documentation for open for more details.有关更多详细信息,请参阅open文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM