0

Is there a Python library for reading/writing to files?

Must have features:

  • Python 3 support
  • Single line commands for
    • Reading file into a string
    • Reading file into list of string (each line is one string)
    • Writing string to file
    • Writing list of strings to file (each string is a line)

Being able to specify file path relative to script directory would be nice, but not necessary.

2 Answers 2

4

Maybe I did not understand completely your question, but the standard python libraries os,path do what You want.
You can read a file into a string using read function:

## Read the file and put the content into a string ##
myfilestring = open('myfile','r').read()

You can use readlines to put the file into a list of string

myfileliststring = open('myfile','r').readlines()

To write, the same way, You can use write() function

mystring = "blablablablabla"
fw = open('myfilew','w')
fw.write(mystring)

See the complete documentation about os.path, to fully understand how to use it.

0

It's already there in builtins.

Depending on what you want to do, it's best to do following.

Iterating over lis of files:

for line in open(path, mode):
    ...

This is nice because it uses file object's iterator facilities that conserve memory (lines are read one by one and discarded by gc when not needed anymore).

Read the whole file:

content = open(path, mode).read()

(mode is smth like 'rb', or 'read, binary')

For paths, it's another library: os.path, also included in base installation. os.path.realpath is able to construct actual paths from relative paths IIRC. There's also useful os.path.abspath.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.