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: Thefile.write()method only accepts a single string argument, but your code tries to pass four separate values ('atom', 'x', 'y', 'z'). This would throw aTypeError—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
- Moved input file reading outside the loop: Reading the input file once instead of 270 times saves time and avoids unnecessary I/O operations.
- Used
wmode for writing: This creates a new text file (or overwrites an existing one) for each structure, which is what you want for sequentially namedoutput*.xyzfiles. - 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.
- 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.xyzexists in your current working directory (the path printed byos.getcwd()).- You have write permissions for that directory.
内容的提问来源于stack exchange,提问作者Dragmoogle
相关产品推荐
相关产品推荐

