python - 如何在一行中一起写入打印字符串变量和循环范围变量
问题描述
我试图遍历一系列变量并将它们写入新行的输出文件。
我研究并尝试了 f.write、print()、printf 和 f'。
代码返回频繁的语法错误,或者我传递了太多参数或无法连接字符串和整数。
定义变量
House = range(0,40,10)
.
循环遍历每个变化:
casenumber = 0 #used in the filename
for ham in House:
# CREATE INDIVIDUAL YML (TEXT) FILES
casenumber = casenumber + 1
filename = 'Case%.3d.yml' % casenumber
f = open(filename, 'w')
# The content of the file:
f.write('My House has this many cans of spam', House)
f.close()
解决方案
这应该对你有用,我想你想把数字写到ham
文件中
casenumber = 0 #used in the filename
#Iterate through the range
for ham in range(0,40,10):
# CREATE INDIVIDUAL YML (TEXT) FILES
casenumber = casenumber + 1
filename = 'Case%.3d.yml' % casenumber
f = open(filename, 'w')
# The content of the file:
#I assume you want to write the value of ham in the file
f.write('My House has this many cans of spam {}'.format(ham))
f.close()
我们将在这里得到 4 个文件,其内容在它们前面
Case001.yml #My House has this many cans of spam 0
Case002.yml #My House has this many cans of spam 10
Case003.yml #My House has this many cans of spam 20
Case004.yml #My House has this many cans of spam 30
此外,您还可以使用with
语句打开文件,它将为您关闭文件,如下所示。
casenumber = 0 #used in the filename
#Iterate through the range
for ham in range(0,40,10):
# CREATE INDIVIDUAL YML (TEXT) FILES
casenumber = casenumber + 1
filename = 'Case%.3d.yml' % casenumber
with open(filename, 'w') as f:
# The content of the file:
#I assume you want to write the value of ham in the file
f.write('My House has this many cans of spam {}'.format(ham))
推荐阅读
- python - 如何提高在 python 中使用循环处理 numpy 数组的计算效率?
- python - Python 简单 spyne SOAP web 服务响应慢
- loops - 如何在 julia 中使用数组元素作为迭代器?
- android - 如何将 AnyChart-Android 导入 Android Studio
- c# - 在文本框中自动显示值
- powershell - 在不同域之间复制数据
- batch-file - 批量“for”命令从 TSV 文件中提取列
- session - pine 脚本 v4:会话范围问题
- c++ - Z3:如何在不使用硬编码索引的情况下从 model() 访问变量?
- android - DefaultNetworkCallback 用于检查网络连接未成功更新全局状态变量