如何使用python将下面的测试准确写入文本文件?当我必须用不同的参数写几个文本文件时,这是必需的。
MY_FILE = E:\test.jpg
BAND_SUBSET = ( 1 0 0 )
SPATIAL_SUBSET1 = ( 25.0 50.0 )
SPATIAL_SUBSET2 = ( 25.0 50.0 )
PARA1 = (
0.0 0.0 0.0
0.0 0.0 0.0 )
END = END
答案 0 :(得分:1)
with open('somefile.txt', 'w') as fp:
fp.write('''MY_FILE = E:\test.jpg
BAND_SUBSET = ( 1 0 0 )
SPATIAL_SUBSET1 = ( 25.0 50.0 )
SPATIAL_SUBSET2 = ( 25.0 50.0 )
PARA1 = (
0.0 0.0 0.0
0.0 0.0 0.0 )
END = END''')
答案 1 :(得分:0)
with open('fileName', 'w') as f:
f.write(yourString)
,其中
>>> yourString = """MY_FILE = E:\test.jpg
BAND_SUBSET = ( 1 0 0 )
SPATIAL_SUBSET1 = ( 25.0 50.0 )
SPATIAL_SUBSET2 = ( 25.0 50.0 )
PARA1 = (
0.0 0.0 0.0
0.0 0.0 0.0 )
END = END"""
您可以使用以下代码替换值。
with open('fileName', 'w') as f:
f.write(yourString.format(band_subset, spatial_subset_1, spatial_subset_2, para1))
其中
yourString = """MY_FILE = E:\test.jpg
BAND_SUBSET = {}
SPATIAL_SUBSET1 = {}
SPATIAL_SUBSET2 = {}
PARA1 = {}
END = END"""
始终使用help
功能或参阅Python文档。
write(...)
write(str) -> None. Write string str to file.