DISQUS

DISQUS Hello! techniQal support is using DISQUS, a powerful comment system, to manage its comments. Learn more.

Community Page

techniQal support

the Q stands for quality
Jump to original thread »
Author

Python: Simple File Read and Write

Started by Daniel · 1 year ago

Though there are a lot of resources out there for Python, rarely do you find a simple reference guide that helps you navigate the basics. I found that there was not a lot of reference material to help you do the simple things, if you didn’t know what to look for.

This little guide will focus [...] ... Continue reading »

6 comments

  • Hi, I have opened my file I have manipulated and I want save this new change in the other directory. At least I know that I should be use ' r ' for reading and ' w ' command for writing, but I do not know how I can make connection between readings and manipulate file and writing this manipulation in the other file.
    Best Regards
    Reza _ Finland
  • All you need to do is specify the location of the file you want to save to.

    So when opening the second file, specify the directory then.
    Example on win32:
    file = open("my_dir\\newfile.txt","w")
    Example on *nix :
    file = open("my_dir/newfile.txt","w")

    This will create the new file in the directory "my_dir" assuming the directory exists in the same folder as your python script. You can also specify an absolute file path as well.
  • Thank you Daniel, another problem:
    x = [0,1,2,3]
    GeneCode = ['AAAA','AAAC','AAAG','AAAT']
    def Li_to_GC(x):
    for i in x:
    print GeneCode[i],
    Li_to_GC(x)

    How can convert the result to the list or string?
  • Well,
    I would argue that the input is a list already. If you are wanting to return a subset of the GeneCode list, I would do the following. There are more graceful ways to achieve this, but this method shows you the logic involved.

    x = [0,1,2,3]
    GeneCode = ['AAAA','AAAC','AAAG','AAAT']

    def Li_to_GC(x):
    newList = [GeneCode[i] for i in x]
    return newList

    print Li_to_GC(x)



    In this case, you can then pass any numeric list to LI_to_GC and get the corresponding Genecodes list back.
    I would check out this great List comprehension article here, and you can learn more. http://effbot.org/zone/python-list.htm
  • hi, how would you read the whole file in but exclude say the first 4 bytes of it?
    thanks
    sean
  • Hi,
    I am opening a file in r+ mode. I have a problem in this. If I first write in a file and then read the same file it is working fine. But some junk characters are added to the end of the string.
    Also one more problem if I read it first say using readline function and then write it, the write operation doesn't happen. Any idea what might be the problem?

Add New Comment

Returning? Login