Python 文件字典 - 如何实现?

发布于 2024-10-20 14:21:28 字数 728 浏览 2 评论 0原文

我需要动态打开一些新的 csv 文件,具体取决于 infile 包含的数据。这些 csv 文件需要具有基于此数据的文件名,因此不能对它们进行硬编码。

我正在尝试制作 {filename,FILENAME.CSV} 的字典,但在处理以下几行时遇到了问题:

    if not os.path.exists(filename):
        files_dict[filename] = open(filename,'w')
    files_dict[filename].write('Test')

if 语句工作正常 - 它会很高兴地通过 infile 创建所有必要的 csv 文件。

但它不喜欢 write 语句:

Traceback (most recent call last):
  File "R:\DataTeam\Orange\Landline\Fixed\Websource_Landline_FixedData_SplitIntoAccounts_20110307.py", line 141, in <module>
    files_dict[filename].write('Test')
KeyError: 'OBS Fixed 6-65544 - BRICO DEPOT 201005.csv'

关于如何写入这些已成功创建的文件有什么想法吗?或者有更简单的方法来做到这一点吗?

谢谢,

托尼

I need to open some new csv files on the fly, depending on what data the infile contains. These csv files need to have filenames based on this data so they can't be hard coded.

I'm trying to make a dictionary of {filename,FILENAME.CSV}, and am having trouble with the lines below:

    if not os.path.exists(filename):
        files_dict[filename] = open(filename,'w')
    files_dict[filename].write('Test')

The if statement works fine - it will happily go through the infile creating all the necessary csv files.

It doesn't like the write statement though:

Traceback (most recent call last):
  File "R:\DataTeam\Orange\Landline\Fixed\Websource_Landline_FixedData_SplitIntoAccounts_20110307.py", line 141, in <module>
    files_dict[filename].write('Test')
KeyError: 'OBS Fixed 6-65544 - BRICO DEPOT 201005.csv'

Any ideas on how to write to these files that have been successfully created? Or is there a much easier way to do this?

Thanks,

Tony

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多彩岁月 2024-10-27 14:21:28

问题在于,如果文件已经存在,则您不会打开该文件或将文件名分配为字典中的键,因此会出现 KeyError 异常。

试试这个:

# open file if not yet open
files_dict.setdefault(filename, open(filename,'w')) 
files_dict[filename].write("test")

如果文件名尚不存在于字典中,这会以写入模式打开一个文件,并将处理程序存储在字典中,并以文件名作为键。请注意,已存在但尚未分配给字典的文件将被覆盖。

如果您只执行一次写入,则可以合并这些行,因为 setdefault 将返回分配给该键的值。

files_dict.setdefault(filename, open(filename,'w')).write("test")

The problem lies with the fact that if the file already exists, you are not opening the file or assigning the filename as a key in the dict, hence the KeyError exception.

Try this instead:

# open file if not yet open
files_dict.setdefault(filename, open(filename,'w')) 
files_dict[filename].write("test")

This opens a file in write mode if the filename does not yet exist in the dict, and stores the handler in the dict with the filename as the key. Note that files that already exists but has not yet been assigned to the dict will be overwritten.

If you are only performing a single write, you can combine the lines since setdefault will return the value assigned to the key.

files_dict.setdefault(filename, open(filename,'w')).write("test")
猫九 2024-10-27 14:21:28

Shawn Chin 提出的解决方案确实消除了错误,但它引入了一个微妙的错误:setdefault 的第二个参数是一个值,而不是需要时调用的函数;因此,每次调用 setdefault 时都会调用 open(filename,'w') 。这会导致额外的文件句柄可能与同一程序中现有的打开句柄冲突,并且会产生“有效的 Python:编写更好的 Python 的 90 种特定方法,第二版”中讨论的许多后果。本书提供了一个更复杂的解决方案,但像这样简单的解决方案可能就足够了:

if filename in files_dict:
    file = files_dict[filename]
else:
    file = open(filename,'w')
    files_dict[filename] = file
file.print("test")

Shawn Chin's proposed solution does indeed remove the error, but it introduces a subtle bug: setdefault's 2nd parameter is a value, not a function called when needed; therefore, open(filename,'w') is called every time setdefault is called. This results in an additional file handle that may conflict with existing open handles in the same program, and it has a number of consequences discussed in "Effective Python: 90 Specific Ways to Write Better Python, 2nd Edition". The book provides a more sophisticated solution, but something simple like this may suffice:

if filename in files_dict:
    file = files_dict[filename]
else:
    file = open(filename,'w')
    files_dict[filename] = file
file.print("test")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文