Read entire file: Difference between revisions
(added PowerShell) |
(→{{header|PowerShell}}: return a string) |
||
Line 17: | Line 17: | ||
With explicit selection of encoding: |
With explicit selection of encoding: |
||
<lang powershell>Get-Content foo.txt -Encoding UTF8</lang> |
<lang powershell>Get-Content foo.txt -Encoding UTF8</lang> |
||
However, both return an array of strings which is fine for pipeline use but if a single string is desired the array needs to be joined: |
|||
<lang powershell>(Get-Content foo.txt) -join "`n"</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
Revision as of 16:27, 29 June 2010
You are encouraged to solve this task according to the task description, using any language you may know.
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check File IO); this is for those cases where having the entire file is actually what is wanted.
E
<lang e><file:foo.txt>.getText()</lang>
The file is assumed to be in the default encoding.
PowerShell
<lang powershell>Get-Content foo.txt</lang> With explicit selection of encoding: <lang powershell>Get-Content foo.txt -Encoding UTF8</lang> However, both return an array of strings which is fine for pipeline use but if a single string is desired the array needs to be joined: <lang powershell>(Get-Content foo.txt) -join "`n"</lang>
Python
<lang python>open(filename).read()</lang>
This returns a byte string and does not assume any particular encoding.