1

How can I write exactly the test below using python into a text file? This is required when I have to write several text files with different parameters.

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

2 Answers 2

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''')
Sign up to request clarification or add additional context in comments.

2 Comments

yes, but i have to input band_subset, para1 etc from program, i mean they are defined as variable Sukrit Kalra @ Ignacio Vazquez-Abrams
So what. Are you asking how to put them into a string?
0
with open('fileName', 'w') as f:
    f.write(yourString)

where

>>> 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"""

You could replace the values by using the following code.

with open('fileName', 'w') as f:
    f.write(yourString.format(band_subset, spatial_subset_1, spatial_subset_2, para1))

where

yourString = """MY_FILE = E:\test.jpg

BAND_SUBSET = {}

SPATIAL_SUBSET1 = {}
SPATIAL_SUBSET2 = {}

PARA1 = {}

END = END"""

Always use the help function or consult The Python Docs.

write(...)
    write(str) -> None.  Write string str to file.

4 Comments

yes, but i have to input band_subset, para1 etc from program, i mean they are defined as variable Sukrit Kalra @Sukrit Kalra
How are your variables stored? As Tuples?
as string @Sukrit Kalra
thank you , i accepted your answer. could you please explain me the meaning of """ @Sukrit Kalra

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.