简体   繁体   中英

Python read-modify-write line

I'm doing some editing on a file line by line

what i would like to do is the following i have a line and i want to use delimiter to split it and take the first argument after delimiter which is space.

for line in file1:
  line = line.strip();
  new = line.split(" ")[1]+"\n";      
  file2.write(new);
file2.close();
file2  = open("temp.hex",'r');


for line in file2:

as you can see the way i do it as split the line by delimiter and write it to new file. then i want to do some more editing so i must close and reopen file to iterate it line by line

my questions are 1. can i modify the line originally on file1? 2. do i must close file2 before i scan it again line by line?

Thanks allot, Jonathan

FYI you don't need semicolons in Python. They don't harm your code, but they aren't necessary either.

You can combine multiple open calls with the with statement which will also close the files implicitly after program exits:

with open('a', 'r') as file1 and open('b', 'w') as file2:
    for line in file1:
        line = line.strip()
        new = line.split(" ")[1]+"\n"
        file2.write(new)

        # do additional editing

Because the reputation limit on comments i need to write here to answer to xPino from ILostMySpoon answer:

with open('a', 'r') as file1 and open('b', 'w') as file2:
    for line in file1:
        line = line.strip()
        new = line.split(" ")[1]+"\n"
        file2.write(new)

    # do additional editing 
  1. opening a with only read atr as file1 [ file1 = fopen('filename','attributes') ] same with file2
  2. for every line in the file1
  3. line = line.strip() remove the whitespace in the end of the line
  4. new = the line is splitted everywhere theres a whitespace and added the \\n in the end.
  5. write out new into the file 2.

Its will rewrite the file 2 everytime if im right i would use append in file2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM