-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpythonfile.nim
329 lines (244 loc) · 9.68 KB
/
pythonfile.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# Nim module to wrap the file functions and provide an interface
# as similar as possible to that of Python.
# Written by Adam Chesak.
# Released under the MIT open source license.
## pythonfile is a Nim module to wrap the file functions and provide an interface as similar as possible to that of Python.
##
## Examples:
##
## .. code-block:: nimrod
##
## # Open a file for reading, read and print one line, then read and store the next ten bytes.
## var f: PythonFile = open("my_file.txt", "r") # f = open("my_file.txt", "r")
## echo(f.readline()) # print(f.readline())
## var s: string = f.read(10) # s = f.read(10)
## f.close() # f.close()
##
## .. code-block:: nimrod
##
## # Open a file for writing, write "Hello World!", then write multiple lines at once.
## var f: PythonFile = open("my_file.txt", "w") # f = open("my_file.txt", "w")
## f.write("Hello World!") # f.write("Hello World!")
## f.writelines(["This", "is", "an", "example"]) # f.writelines(["This", "is", "an", "example"])
## f.close() # f.close()
##
## .. code-block:: nimrod
##
## # Open a file for reading or writing, then read and write from multiple locations
## # using seek() and tell().
## var f: PythonFile = open("my_file.txt", "r+") # f = open("my_file.txt", "r+")
## f.seek(10) # f.seek(10)
## echo(f.read()) # print(f.read())
## echo(f.tell()) # print(f.tell())
## f.seek(0) # f.seek(0)
## f.seek(-50, 2) # f.seek(-50, 2)
## f.write("Inserted at pos 50 from end") # f.write("Inserted at pos 50 from end")
## f.close() # f.close()
##
## Note that due to some inherent differences between how Nim and Python handle files, a complete
## 1 to 1 wrapper is not possible. Notably, Nim has no equivalent to the ``newlines`` and ``encoding``
## properties, and while they are present in this implementation they are always set to ``nil``. In
## addition, the ``fileno()`` procedure functions differently from how it does in Python, yet it has the
## same basic functionality. Finally, the ``itatty()`` procedure will always return ``false``.
##
## For general use, however, this wrapper provides all of the common Python file methods.
import macros, strutils, terminal
when defined(Unix):
import posix
type
PythonFile* = ref object
f*: File
mode*: string
closed*: bool
name*: string
softspace*: bool
encoding*: string
newlines*: string
filename*: string
macro with*(args: untyped, body: untyped): untyped =
### A with macro.
args.expectKind nnkInfix
args.expectLen 3
# basic stmt
var stmt = newStmtList()
stmt.add newTree(nnkVarSection,
newIdentDefs(
args[2],
newEmptyNode(),
args[1]
)
)
for i in body: stmt.add i
stmt.add newTree(nnkCall,
newDotExpr(
args[2],
newIdentNode("close")
)
)
# add basic stmt to block stmt, for better exception catch
result = newStmtList()
result.add newTree(nnkBlockStmt,
newEmptyNode(),
stmt
)
proc open*(filename: string, mode: string = "r", buffering: int = -1): PythonFile =
## Opens the specified file.
##
## mode can be either ``r`` (reading), ``w`` (writing), ``a`` (appending), ``r+`` (read/write, only existing files), and ``w+``
## (read/write, file created if needed).
##
## ``buffering`` specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means
## use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually
## line buffered for tty devices and fully buffered for other files.
var f: PythonFile = PythonFile(f: nil, mode: mode, closed: false, softspace: false, encoding: "", newlines: "", filename: filename)
var m: FileMode
case mode:
of "r", "rb":
m = fmRead
of "w", "wb":
m = fmWrite
of "a", "ab":
m = fmAppend
of "r+", "rb+":
m = fmReadWriteExisting
of "w+", "wb+":
m = fmReadWrite
else:
m = fmRead
f.f = open(filename, m, buffering)
return f
proc close*(file: PythonFile): void =
## Closes the file.
file.f.close()
file.closed = true
proc tell*(file: PythonFile): int =
## Returns the file's current position.
return int(file.f.getFilePos())
proc seek*(file: PythonFile, offset: int): void =
## Sets the file's current position to the specified value.
file.f.setFilePos(offset)
proc seek*(file: PythonFile, offset: int, whence: int): void =
## Sets the file's current position to the specified value. ``whence`` can be either 0 (absolute positioning),
## 1 (seek relative to current position), or 2 (seek relative to file's end).
case whence:
of 0:
file.seek(offset)
of 1:
file.seek(file.tell() + offset)
of 2:
file.seek(int(file.f.getFileSize()) + offset)
else:
file.seek(offset)
proc write*(file: PythonFile, s: string): void =
## Writes ``s`` to the file.
file.f.write(s)
proc write*(file: PythonFile, s: float32): void =
## Writes ``s`` to the file.
file.f.write(s)
proc write*(file: PythonFile, s: int): void =
## Writes ``s`` to the file.
file.f.write(s)
proc write*(file: PythonFile, s: BiggestInt): void =
## Writes ``s`` to the file.
file.f.write(s)
proc write*(file: PythonFile, s: BiggestFloat): void =
## Writes ``s`` to the file.
file.f.write(s)
proc write*(file: PythonFile, s: bool): void =
## Writes ``s`` to the file.
file.f.write(s)
proc write*(file: PythonFile, s: char): void =
## Writes ``s`` to the file.
file.f.write(s)
proc write*(file: PythonFile, s: cstring): void =
## Writes ``s`` to the file.
file.f.write(s)
proc read*(file: PythonFile): string =
## Reads all of the contents of the file.
let pos = int(file.f.getFilePos())
file.f.setFilePos(0)
return file.f.readAll().substr(pos)
proc read*(file: PythonFile, count: int): string =
## Reads the specified number of bytes from the file.
var chars: seq[char] = newSeq[char](count)
discard file.f.readChars(chars, 0, count)
return chars.join()
proc readline*(file: PythonFile): string =
## Reads a line from the file.
let line: string = file.f.readLine()
if file.f.endOfFile():
return line
else:
return line & "\n"
proc readline*(file: PythonFile, count: int): string =
## Reads a line from the file, up to a maximum of the specified number of bytes.
let line: string = file.readLine()
if len(line) <= count:
return line
else:
file.seek(-1 * (len(line) - count), 1)
return line.substr(0, count)
proc readlines*(file: PythonFile): seq[string] =
## Reads all of the lines from the file.
file.f.setFilePos(0)
let contents: string = file.read()
file.f.setFilePos(0)
var lines: seq[string] = @[]
for index in 0..countLines(contents):
if file.f.endOfFile():
break
lines.add(file.readline())
return lines
proc readlines*(file: PythonFile, count: int): seq[string] =
## Reads all of the lines from the file, up to a maximum of the specified number of bytes.
file.f.setFilePos(0)
let contents: string = file.read()
file.f.setFilePos(0)
var lines: seq[string]= newSeq[string](countLines(contents))
var charCount: int = 0
for index in 0..countlines(contents):
if file.f.endOfFile():
break
let line: string = file.readLine()
charCount += len(line)
if charCount < count:
lines[index] = line
elif charCount > count:
var diff: int = len(line) - (charCount - count)
lines[index] = line.substr(0, diff)
file.seek(-1 * (charCount - count), 1)
break
else:
lines[index] = line
break
return lines
proc flush*(file: PythonFile): void =
## Flushes the file's internal buffer.
file.f.flushFile()
proc fileno*(file: PythonFile): FileHandle =
## Returns the underlying file handle. Note that due to implementation details this is NOT the same in Nim as it
## is in Python and CANNOT be used the same way!
return file.f.getfileHandle()
proc writelines*(file: PythonFile, lines: openarray[string]): void =
## Writes the lines to the file.
for line in lines:
file.write(line)
proc isatty*(file: PythonFile): bool =
## Returns true if the opened file is a tty device, else returns false
return file.f.isatty()
proc truncate*(file: PythonFile, length: int): int =
## Truncate the file to a specify size, returns 0 if successed, else returns -1.
## TODO: add support for windows platform.
when defined(Unix):
result = ftruncate(file.f.getFileHandle(), length)
if result == 0: file.seek(0, 0)
elif defined(Windows):
result = 0
when isMainModule:
## test code
with open("temp.txt", "w+") as f:
f.write("test")
f.seek(0, 0)
echo(f.read())
import os
os.removeFile("temp.txt")