我收到的错误是:
_csv。错误:迭代器应返回字符串,而不是字节(您是否以文本模式打开文件?)
我将在文本代码中的什么位置打开文件?
import csv
import urllib.request
import pymysql.cursors
connection = pymysql.connect(host='localhost',
user='',
password='',
db='mydb',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
try:
url = 'https://api.iextrading.com/1.0/stock/market/collection/sector?
collectionName=Health%20Care&format=csv'
response = urllib.request.urlopen(url)
csv_data = csv.reader(response)
for row in csv_data:
cursor.execute('INSERT INTO Financials (names, \
classes, mark )' \
'VALUES("%s", "%s", "%s")',
row)
finally:
connection.close()
答案 0 :(得分:1)
@RestController
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/api/auth/signup")
public ResponseEntity<RestResponse> registerUser(@Valid @RequestBody SignUpRequest signUpRequest,
UriComponentsBuilder uriComponentsBuilder) {
RestResponse restResponse = this.userService.register(signUpRequest);
UriComponents uriComponents = uriComponentsBuilder.path("/users").buildAndExpand();
return ResponseEntity.created(uriComponents.toUri()).body(restResponse);
}
@PostMapping("/api/auth/signin")
public ResponseEntity<JwtAuthenticationResponse> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
return ResponseEntity.ok(this.userService.login(loginRequest));
}
}
此处response = urllib.request.urlopen(url)
返回response
对象上的迭代器。
如果您知道csv文件只是纯文本,则可以插入生成器理解以解码行:
bytes
或csv_data = csv.reader(line.decode() for line in response)
(当您不使用map
就可以使用python 3 map
吗?)
lambda
独立的示例:
csv_data = csv.reader(map(bytes.decode,response))
现在您要向import urllib.request,csv
url = 'https://api.iextrading.com/1.0/stock/market/collection/sector?collectionName=Health%20Care&format=csv'
response = urllib.request.urlopen(url)
for row in csv.reader(line.decode() for line in response):
print(row)
提供一系列字符串,这将起作用。
示例输出:
csv.reader