You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环生成不同命名文件并写入:代码无报错但未生成文件求助

Troubleshooting & Fix: No Output Files Generated in Your Python Loop

Let's walk through the issues in your code and fix them so those output*.xyz files start appearing as expected:

Key Problems in Your Original Code

  • Incorrect file writing mode: You used ab (binary append) mode for writing text-based XYZ files. This mode is designed for binary data, not plain text, which can cause files to be created but appear empty/unreadable, or even prevent them from being generated properly.
  • Invalid write() call: The file.write() method only accepts a single string argument, but your code tries to pass four separate values ('atom', 'x', 'y', 'z'). This would throw a TypeError—if you didn't see an error, it means this part of your code isn't executing as written, or your actual implementation still isn't writing valid content.
  • Missing proper data output: You read the input data into a pandas DataFrame but never wrote the processed data to the output files. Just trying to write column names won't produce a valid XYZ file anyway, since XYZ has a specific format (atom count first, then a comment line, then atomic coordinates).

Fixed Code Example

Here's a revised version that addresses all these issues, plus some efficiency improvements:

import pandas as pd
import os

# Optional: Verify current working directory to ensure files are in the right place
print(f"Current working directory: {os.getcwd()}")

number_structures = 270

# Read the input XYZ file ONCE outside the loop (no need to re-read it 270 times)
with open('FeCO5.xyz', 'r') as inputfile:
    # Capture the required XYZ header lines
    atom_count = inputfile.readline().strip()
    comment_line = inputfile.readline().strip()
    # Read the atomic coordinate data into a DataFrame
    molecule = pd.read_table(
        inputfile,
        delim_whitespace=True,
        names=['atom', 'x', 'y', 'z']
    )

for i in range(number_structures):
    # --------------------------
    # Insert your data processing logic here
    # Example: Modify coordinates (replace this with your actual operations)
    modified_mol = molecule.copy()
    modified_mol['x'] += i  # Shift x-coordinate by i for demo purposes
    # --------------------------

    # Use 'w' mode to create a new text file for each iteration
    with open(f'output{i}.xyz', 'w') as f:
        # Write the standard XYZ file header
        f.write(f"{atom_count}\n")
        f.write(f"{comment_line} - Structure {i}\n")
        # Write the processed coordinates without index or header
        modified_mol.to_csv(f, sep=' ', index=False, header=False)

What Changed & Why

  1. Moved input file reading outside the loop: Reading the input file once instead of 270 times saves time and avoids unnecessary I/O operations.
  2. Used w mode for writing: This creates a new text file (or overwrites an existing one) for each structure, which is what you want for sequentially named output*.xyz files.
  3. Followed XYZ file format: Properly writes the atom count, a comment line, and then the atomic coordinates—this ensures the output files are valid and readable by other chemistry tools.
  4. Valid Data Output: Uses pandas' to_csv() to correctly write the processed DataFrame to the file, with spaces as separators (standard for XYZ) and no extra index/header lines.

Additional Check

If you still don't see files after running this, double-check that:

  • FeCO5.xyz exists in your current working directory (the path printed by os.getcwd()).
  • You have write permissions for that directory.

内容的提问来源于stack exchange,提问作者Dragmoogle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:17:55